gpt4 book ai didi

java - 同步块(synchronized block)中的等待线程

转载 作者:行者123 更新时间:2023-11-30 11:13:15 25 4
gpt4 key购买 nike

如果我有这些功能

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

}

并且可以进入 synchronized block 内部的线程,

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 锁定?

是否可以使用(并发 API)的 Lock 和条件重写 methodA()?

最佳答案

是的,Thread3 会等到锁被释放。

你正在从Lock接口(interface)中寻找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

关于java - 同步块(synchronized block)中的等待线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26505414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com