2014-10-22 191 views
2

如果我有這些功能等待的線程

public void methodA(){ 
      synchronized (ObjectAlwaysDifferent) { 
      .... 
      } 
    } 
public void methodB(){ 

} 

而且可以在​​塊,進入裏面的線程,

Thread1 enter with Object1 
Thread2 enter with Object2 

而另一個線程

Thread3 want to enter with Object1 

如果線程循環爲:

public void run(){ 
    while(true){ 
    methodA(); 
    methodB(); 
    } 
} 

thread3會在methodA之內等待,直到object1的lock會被釋放? 或者如果監視器對象被另一個thread鎖定,它能夠執行methoB

有可能使用Lock和condition(併發API)重寫methodA()方法嗎?

回答

1

是的,Thread3會一直等到鎖定被釋放。

您從尋找的tryLock()鎖定接口

docs

boolean tryLock() 
Acquires the lock only if it is free at the time of invocation. 
Acquires the lock if it is available and returns immediately with the value true. If the lock is not available then this method will return immediately with the value false. 

A typical usage idiom for this method would be: 

     Lock lock = ...; 
     if (lock.tryLock()) { 
      try { 
       // manipulate protected state 
      } finally { 
       lock.unlock(); 
      } 
     } else { 
      // perform alternative actions 
     } 

This usage ensures that the lock is unlocked if it was acquired, and doesn't try to unlock if the lock was not acquired. 
Returns: 
true if the lock was acquired and false otherwise 
+0

感謝您的回答,所以它仍然是了methodA(內),它會不會執行methoB ()如果它不消耗methodA。 – 2014-10-22 10:41:35

+1

它會等到鎖定被釋放,是的。另外請記住,如果有很多線程,釋放鎖定時不保證順序(隨機線程將擁有鎖定,而不是通過鎖定請求的順序)。如果這對你很重要,請考慮使用ReentrantLock。 – bmartins 2014-10-22 10:44:25