簡體   English   中英

Java線程同步死鎖wait(); notifyAll();

[英]Java Thread synchronized Deadlock wait(); notifyAll();

由於您使用的是Thread ,因此下面的代碼可能給出如下結果:

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

然后,代碼將運行直到遇到死鎖。 為什么在上面的輸出中缺少Notified...One 需要說明...(多次執行以下代碼時,您可以獲得與上述類似的結果)

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();
    }
}

你只是有一個種族條件。 變量t引用的線程可能在t1引用的線程執行waitThread(..)方法之前執行notifyAll() 這不是僵局。 您的某些等待只是在notifyAll()之后發生。

您面臨的是虛假喚醒的問題,因此發生了什么情況,通知所有其他線程的線程可能更早地調用了另一個線程,並且在另一個線程運行之后等待喚醒。線程完成。

更改您的代碼...

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();
   }   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM