2016-12-13 4 views
0

Code 1:Java unendlich warten Frage?

class BCWCExamples { 
    public Object lock; 

    boolean someCondition; 

    public void NoChecking() throws InterruptedException { 
     synchronized(lock) { 
      //Defect due to not checking a wait condition at all 
      lock.wait(); 
     } 
    } 

Code 2:

public void IfCheck() throws InterruptedException { 
      synchronized(lock) { 
       // Defect due to not checking the wait condition with a loop. 
       // If the wait is woken up by a spurious wakeup, we may continue 
       // without someCondition becoming true. 
       if(!someCondition) { 
        lock.wait(); 
       } 
      } 
     } 

Code 3:

public void OutsideLockLoop() throws InterruptedException { 
      // Defect. It is possible for someCondition to become true after 
      // the check but before acquiring the lock. This would cause this thread 
      // to wait unnecessarily, potentially for quite a long time. 
      while(!someCondition) { 
       synchronized(lock) { 
        lock.wait(); 
       } 
      } 
     } 

Code 4:

public void Correct() throws InterruptedException { 
      // Correct checking of the wait condition. The condition is checked 
      // before waiting inside the locked region, and is rechecked after wait 
      // returns. 
      synchronized(lock) { 
       while(!someCondition) { 
        lock.wait(); 
       } 
      } 
     } 
    }  

Anmerkung: es aus einem anderen wird benachrichtigen Platz

gibt es keine Bedingung für die Wartezeit in Code 1 so unendlich warten dort ist, aber warum die unendliche Wartezeit wird in anderen 3-Code auftritt (2,3,4)
freundlich überprüfen Sie die Kommentare in den Code für ein besseres Verständnis bitte helfen Sie mir Ich bin neu in Java warten und benachrichtigen

+0

Ist das der entireity des entsprechenden Codes? Der Wert someCondition wird niemals auf true gesetzt –

Antwort