【发布时间】:2013-07-01 06:51:26
【问题描述】:
我正在尝试检查等待/通知在 java 中的工作方式。
代码:
public class Tester {
public static void main(String[] args) {
MyRunnable r = new MyRunnable();
Thread t = new Thread(r);
t.start();
synchronized (t) {
try {
System.out.println("wating for t to complete");
t.wait();
System.out.println("wait over");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("entering run method");
synchronized (this) {
System.out.println("entering syncronised block");
notify();
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("leaving syncronized block");
}
System.out.println("leaving run method");
}
}
输出返回
wating for t to complete
entering run method
entering syncronised block
//sleep called
leaving syncronized block
leaving run method
wait over
我期待在执行 notify() 时等待将结束,System.out.println("wait over"); 将被打印出来。但它似乎只有在t 完成其run() 时才会被打印出来。
【问题讨论】:
-
你没有在同一个对象上同步
-
MyRunnable.this == r != t
-
@raul8 编辑问题并粘贴答案会使正确答案无效。最好再补充一个问题。
-
我了解到您正在研究
wait/notify的工作原理。但无论如何,我强烈建议您在代码中使用 Java 的 high level concurrent API。在低级并发代码中很容易犯难以发现的错误(正如您在本示例中所见)。
标签: java multithreading synchronization