【发布时间】:2016-03-21 09:01:24
【问题描述】:
我有 2 个线程要与 wait() 和 notify() 同步。但是,当我通知等待的线程永远不会恢复时。这是我的代码片段。 在 Lib60870 中,我启动了两个线程,并且线程 HandShake 与 SerialReader 同步。
public Lib60870(){ //Here I start threads
try {
myConnection=new Connection(LOCALHOST,port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mySerialReader.start();
myHandshake.start();}
}
类 SerialReader
public class SerialReader extends Thread {
private static boolean isPaused=true;
@Override
public void run() {
synchronized(this){
if(Lib60870.myConnection!=null){
while(true){
if(!isPaused){
byte inByte=Lib60870.myConnection.getByte();
if(inByte==0x68){
...
}
notify();
}
else if(inByte==0x10){
...
}
notify();
}
}
}
}
}
}
public void setPause(boolean pause){
isPaused=pause;
}
班级握手
public class HandShake extends Thread {
public void run() {
synchronized(Lib60870.mySerialReader){
Lib60870.mySerialReader.setPause(false);
...
try {
Lib60870.mySerialReader.wait();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Lib60870.mySerialReader.setPause(true);
...
Lib60870.mySerialReader.setPause(false);
try {
Lib60870.mySerialReader.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
提前致谢
【问题讨论】:
标签: java multithreading wait notify