java中的wait唤醒_Java wait()不会被notify()唤醒

哈罗我已经整天调试了我的代码,但是我看不出哪里出了问题。

我在主线程上使用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.");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值