public class WaitTest { 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()"); //notify();//notify之后 要等到这个代码块结束之后才会把锁让出去,当然如果在notify之后又有wait,那就会主动把锁让出去 try { System.out.println(Thread.currentThread().getName()+" wait"); //wait(); //Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" after notify"); } } } public static void main(String[] args) throws InterruptedException { ThreadA t1 =new ThreadA("t1"); synchronized (t1){ System.out.println(Thread.currentThread().getName()+" start t1"); t1.start(); System.out.println(Thread.currentThread().getName()+" wait"); t1.wait();// //System.out.println(Thread.currentThread().getName()+" notify"); // t1.notify(); System.out.println(t1.getName()); System.out.println(Thread.currentThread().getName()+" continue"); //t1.notify(); } } }
Logically speaking, t1.wait() should block the main thread, and there is no other place to notify
After removing t1.start(), it can block it
What does this mean? Compiler optimization? Or if the monitor is not operated within the synchronized code block, the active notify will end? ?
It’s not optimization. Actually, it’s related to the execution of threads. In the java doc,
public final synchronized void join(long millis)
The comment of this method has a sentence written on itSee the boldface, it is actually the notifyAll called after the thread ends that causes wait to wake up. It is not caused by any virtual machine optimization. Hope it can answer your confusion