我试图发送一个口袋,如果响应是“!”,则在3秒钟之前。然后,会有通知。
但是,当我收到“!”时,等待方法会中断并停止工作。
线程while(true)出现此问题,我不知道如何解决它
Test datagram; //its current class
DatagramSocket ds;
String adress;
private final Object monitor = new Object();
//send masage
void send(String str, String adress) throws IOException {
synchronized (monitor) {
datagram = this;
this.adress = adress;
ds = new DatagramSocket(3333);
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), InetAddress.getByName(adress), 3333);
try {
ds.send(dp);
receive.start();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
monitor.wait(3000);
System.out.println("send");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Thread receive = new Thread() {
public void run() {
synchronized (datagram.monitor) {
while (true) {//this while make problem
DatagramPacket dp = new DatagramPacket(new byte[2048], 2048);
try {
ds.receive(dp);
String data = new String(dp.getData(), 0, dp.getLength());
if (data.equals("!")) {
System.out.println(data);
this.join();
datagram.monitor.notify();
} else {
ds.send(new DatagramPacket("!".getBytes(), 1, InetAddress.getByName(adress), 3333));
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
};
我在两台计算机上运行此代码 电脑一: new Test()。send(“salam”,“192.168.1.103”); 电脑二: new Test();
答案 0 :(得分:0)
这个问题发生线索线程没有实现锁定
Thread receive = new Thread() {
public void run() {
while (true) {
DatagramPacket dp = new DatagramPacket(new byte[2048], 2048);
try {
ds.receive(dp);
data = new String(dp.getData(), 0, dp.getLength());
if (data.equals("!")) {
synchronized (datagram.monitor) {
datagram.monitor.notify();
}
} else {
ds.send(new DatagramPacket("!".getBytes(), 1, InetAddress.getByName(adress), 3333));
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
};