简体   繁体   中英

Java Thread synchronized Deadlock wait(); notifyAll();

Since you are using a Thread , the code further below might give results like:

 waiting...One waiting...Three waiting...Two Notified...Two Notified...Three 

Then the code is running until it hits a dead lock. Why is Notified...One missing in the output above? Needs explanation ... (You can get similar result as above when executing following code several time)

class A {
    synchronized void waitThread(String threadName) {
        System.out.println("waiting..." + threadName);
        try {
            wait();
        } catch(InterruptedException e) { }
        System.out.println("Notified..." + threadName);
    }
    synchronized void notifyThread() {
        notifyAll();
    }   
}

class T1 extends Thread {
    A a;
    T1(A r, String n) {
        a = r;
        setName(n);
    }
    public void run() {
        a.waitThread(getName());
    }
}

class T2 extends Thread {
    A a;
    T2(A r, String n) {
        a = r;
        setName(n);
    }
    public void run() {
        a.notifyThread();
    }
}

public class DemoWait {
    public static void main(String args[]) {
        A a1 = new A();
        T1 t1 = new T1(a1,"One");
        T1 t2 = new T1(a1,"Two");
        T1 t3 = new T1(a1,"Three");

        t1.start();
        t2.start();
        t3.start();

        T2 t = new T2(a1,"Four");
        t.start();
    }
}

You simply have a race condition. It's possible that the thread referenced by the variable t executes notifyAll() before the thread referenced by t1 executes the waitThread(..) method. This is not deadlock. Some of your waits just happen after your notifyAll() .

You are facing the problem of Spurious wakeup .So what is happening that the thread which is notifying the all other thread might be call earlier of other thread and after that other thread will run and wait for the wake up.Because of spurious wake up some thread complete.

Change your code...

class A{
     boolean flag=true;

     synchronized void waitThread(String threadName){
     System.out.println("waiting..."+threadName);
     try{
       while(flag){
          wait();
        }
      }catch(InterruptedException e){ }
     System.out.println("Notified..."+threadName);
 }

    synchronized void notifyThread(){
      flag=false;
      notifyAll();
   }   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM