2014-10-22 197 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