如果我有这些功能
public void methodA(){
synchronized (ObjectAlwaysDifferent) {
....
}
}
public void methodB(){
}
可以进入synchronized
块的线程,
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
被释放?
或者它'能够执行methoB
如果它的监视对象被另一个thread
锁定了吗?
可以使用Lock和条件(并发API)重写methodA()吗?
答案 0 :(得分: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