刚刚看到的代码如果在main()中启动一个新线程,那么调用wait()不能阻塞主线程?
static class ThreadA extends Thread {
public ThreadA(String name) {
super(name);
}
@Override
public void run() {
synchronized (this) {
System.out.println(Thread.currentThread().getName() + " call notify()");
}
}
}
public static void main(String[] args) throws InterruptedException {
ThreadA t1 = new ThreadA("t1");
synchronized (t1) {
System.out.println("start: " + Thread.currentThread().getName());
t1.start();
t1.wait();
System.out.println(" -- end -- ");
}
}
,输出是:
start: main
t1 call notify()
-- end --
为什么调用wait()的不阻塞主线程
它阻塞主线程,但它以某种方式被释放。它可能与主线程是最后一个线程有关,因为t1会完成执行。 – matt
但是,如果我只是在同步的bolck中调用wait,它会阻塞主线程。@ matt – chasel
是的,主线程被阻塞,然后你的另一个线程运行,然后主线程由于某种原因而被唤醒。这就是为什么建议不要使用等待,因为可能会有虚假的唤醒。因此,while循环建议或“加入”的建议。 – matt