java – Fragen zu Multithread-Benachrichtigungen
给我你的怀抱
给我你的怀抱 2017-05-17 10:01:54
0
1
544
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();
        }
    }
}

Logisch gesehen sollte t1.wait() den Hauptthread blockieren, und es gibt keinen anderen Ort zum Benachrichtigen
Und nach dem Entfernen von t1.start() wird es blockiert

Was bedeutet das? Compiler-Optimierung? Oder wenn der Monitor nicht innerhalb des synchronisierten Codeblocks betrieben wird, endet die aktive Benachrichtigung? ?

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

Antworte allen(1)
仅有的幸福

并不是优化其实,跟线程的执行有关的。在java doc中,public final synchronized void join(long millis)这个方法的注释上面写着一句话

<p> 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.

看到加黑体,其实是线程结束之后调用的notifyAll导致wait苏醒的。并不是什么虚拟机优化导致的。希望能解答你的困惑

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!