如果有可能性,我需要有人解释另外两个错误! 我想将一个对象发送给多个客户(客户端),但执行它时会出现错误! 第一个是:线程“Thread-2”中的异常java.lang.NullPointerException 在ClientServer.Master $ Worker.send(Master.java:177)
第二个是:java.net.ConnectException:连接被拒绝:连接 at java.net.PlainSocketImpl.socketConnect(Native Method)
public void run() {
for (int k = 0; k < MAX_IT; k++) {
ServerData C = new ServerData(getSousPop(ID), problem);
try {
send(C);// here is the first
Object receiveRequest = receive();
System.out.println("Recept");
if(receiveRequest instanceof ClientData){
Population pop = ((ClientData)receiveRequest).getPop();
LocalePop = pop.clone();
SetReady(ID, true);....
这是工人建构者
public Worker(int ID) {
this.ID = ID;
try {
soc = new Socket(IP[ID], ports[ID]);// and the second is here
in = new ObjectInputStream(soc.getInputStream());
out = new ObjectOutputStream(soc.getOutputStream());
} catch (UnknownHostException ex) {
Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Master.class.getName()).log(Level.SEVERE, null, ex);
}
start();
}
答案 0 :(得分:0)
您在同一个实例中调用start
方法两次,第二次抛出IllegalThreadStateException
。
lunch
方法中的一个start
调用for(int i = 0; i < IP.length; i++) {
workers[i] = new Worker(i);
}
这将调用Worker
构造函数,它也会启动线程:
public Worker(int ID) {
this.ID = ID;
[...]
start();
}
此
for(int i = 0; i < IP.length; i++) {
workers[i].start();
}
将重新遍历线程,然后再次启动它们(使用IllegalThreadStateException
失败)。
删除构造函数中的start
调用或for
周期。