哈罗我已经整天调试了我的代码,但是我看不出哪里出了问题。
我在主线程上使用SerialPortEventListener,在工作线程中,我有一个客户端套接字与服务器通信。由于到达此工作线程之后return,我仍然需要在主线程中完成一些总结工作,因此我想创建一个“伪线程”,在主线程中等待,直到从侦听器onEvent方法通知它为止。
但是这个伪线程似乎一直在等待。
我检查了锁定的线程pseudoThread,它们在Runnable和Listener类中应该具有相同的对象ID。
显示了“ PseudoThread等待中”,但从未显示PseudoThread唤醒。
控制台输出显示:PseudoThread等待.. .. false通知伪线程。
PS如果我创建主类的锁public final Object lock = new
Object();,并更换所有main.pseudoThread有main.lock,我得到java.lang.IllegalMonitorStateException。
private class Pseudo implements Runnable{
Main main;
public Pseudo(Main main) {
this.main = main;
}
@Override
public void run() {
synchronized(main.pseudoThread){
try {
System.out.println("PseudoThread waiting");
main.pseudoThread.wait();
System.out.println("PseudoThread awake");
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
}
}
在主要方法中:
public static void main(String[] args) {
Main main = new Main();
main.initArduino();
//more code. including starting the working thread
main.pseudoThread = new Thread(main.new Pseudo(main));
main.pseudoThread.start();
try {
main.pseudoThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void initArduino() {
arduino = new Arduino(this);
if(!arduino.initialize())
System.exit(1);
}
以及在侦听器类中(它也在主线程中运行)
//class constructor;
public Arduino(Main Main){
this.main = Main;
}
//listening method
public void serialEvent(SerialPortEvent oEvent){
//some code to interract with working thread.
record();
}
private void record(){
synchronized(main.pseudoThread){
main.pseudoThread.notify();
System.out.println("notified pseudothread.");
}
}