【发布时间】:2016-09-10 06:01:51
【问题描述】:
我刚刚写了一个简单的java示例来熟悉等待和通知方法的概念。
想法是当调用notify()时,主线程会打印总和。
MyThread 类
public class MyThread extends Thread {
public int times = 0;
@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 10; i++) {
times += 1;
Thread.sleep(500);
if (i == 5) {
this.notify();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
主类
public class Main {
public static void main(String[] args) {
MyThread t = new MyThread();
synchronized (t) {
t.start();
try {
t.wait();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(t.times);
}
}
}
预期结果
5 但我得到了 10 个。
好吧,我认为当调用notify() 时,主线程将唤醒并执行System.out.println(t.times),它应该给出5。然后run() 将继续直到它完成for 循环,这将更新乘以 10。
非常感谢任何帮助。
【问题讨论】:
-
notify不释放锁。 -
您能否进一步说明这一点。
-
线程没有离开同步块。因此,尽管等待可能返回,但 main 将无法继续运行。
-
谢谢大家。明白了。好吧,在这种情况下,我可以使用 join() 代替。
标签: java multithreading wait notify