【发布时间】:2014-07-09 13:33:34
【问题描述】:
你好,我已经调试了一整天的代码,但我就是看不出哪里有问题。
我在主线程上使用 SerialPortEventListener,在工作线程中我有一个客户端套接字与服务器通信。
由于在这个工作线程到达return 之后,我仍然需要在主线程中完成一些总结工作,我想创建一个在主线程中等待的“伪线程”,直到它从监听器 onEvent 方法得到通知。
但是这个伪线程似乎永远在等待。
我检查了锁定线程pseudoThread,它们在 Runnable 和 Listener 类中应该具有相同的对象 ID。
显示“PseudoThread waiting”,但从未显示 PseudoThread awake。
控制台输出显示: 伪线程等待 .. .. 错误通知伪线程。
PS 如果我在 Main 类中使用 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.");
}
}
【问题讨论】:
-
你为什么要调用interrupt()而不是notify();
-
抱歉,现已更正。我试图通过中断解决这个问题..
-
旁注:在线程实例本身上同步是不好的.. -->
synchronized(main.pseudoThread) -
这段代码编译得好吗?您不能在静态上下文中使用它。 arduino = new Arduino(this);
-
对不起,我修改了我的原始代码以使其更紧凑,但似乎我弄错了。是的,它编译得很好。
标签: java multithreading concurrency