【发布时间】:2017-06-09 08:55:06
【问题描述】:
我有下面的程序有 2 个线程 T1 和 T2。 T1 先运行并进入等待状态。 T2 正在调用通知。为什么 T1 线程不恢复并打印“线程 0 已唤醒”
public class WaitNotifyTest{
public static void main(String[] args) {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " is running");
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is waken up");
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (this) {
try {
Thread.sleep(3000);
System.out.println(Thread.currentThread().getName() + " is running");
notify();
System.out.println(Thread.currentThread().getName() + " notifying");
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
});
t1.start();
t2.start();
}
}
输出为
Thread-0 is running
Thread-1 is running
Thread-1 notifying
请注意,此输出后我的程序不会结束/终止。谁能解释一下为什么我的程序没有终止。
【问题讨论】:
-
您可能需要
notifyAll()而不是通知notifyAll vs notify -
不。我试过这个。它给出了相同的结果。什么都没有改变。
标签: java multithreading wait notify