【发布时间】:2019-04-10 03:01:49
【问题描述】:
为什么 t1 线程 3 秒后无法通知?
public class MyThread extends Thread{
public MyThread(String name) {
super(name);
}
//private int ticket = 100;
public void run() {
synchronized(this) {
System.out.println(Thread.currentThread().getName() + " run ");
while(true)
;
}
}
}
public class MultieThreadTest {
public static void main(String[] args) {
MyThread t1 = new MyThread("t1");
synchronized(t1) {
try {
System.out.println(Thread.currentThread().getName() + " start t1 ");
t1.start();
System.out.println(Thread.currentThread().getName() + " call wait 3000ms");
t1.wait(3000);
System.out.println(Thread.currentThread().getName() + " continue ");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
结果是:
主开始 t1
主调用等待 3000ms
t1 运行
但我认为应该是:
主开始 t1
主调用等待 3000ms
t1 运行
//3秒后
主继续
【问题讨论】:
-
你有两个线程在运行,但它们都在同一个监视器上同步...
-
您的预期不正确。你打电话给
wait(),而不是notify()。您需要阅读 Javadoc。 -
synchronized应该用在同一个对象上。
标签: java multithreading