java - Questions about multi-threaded notify
给我你的怀抱
给我你的怀抱 2017-05-17 10:01:54
0
1
507
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? ?

给我你的怀抱
给我你的怀抱

reply all (1)
仅有的幸福

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 it

This implementation uses a loop of {@code this.wait} calls conditioned on {@code this.isAlive}.As a thread terminates the {@code this.notifyAll} method is invoked. It is recommended that applications not use {@code wait}, {@code notify}, or {@code notifyAll} on {@code Thread} instances.

See 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

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!