gpt4 book ai didi

java - ReentrantLock.tryLock() 没有锁定

转载 作者:搜寻专家 更新时间:2023-11-01 04:06:36 25 4
gpt4 key购买 nike

我想我只是没有看到一些东西,因为我过去已经让它工作了。

我的锁没有持有独占锁,当创建对象的新实例时,tryLock 返回 true 并安排另一个 TimerTask

public class A {
private static Timer timer = new Timer();
private static Lock clean_lock = new ReentrantLock();
private static ConcurrentHashMap<String,B> _b_dict = new ConcurrentHashmap<String,B>();

public A() {
if(clean_lock.tryLock()) {
timer.scheduleAtFixedRate(new TimerTaskThread(), new Date(), 60000);
}
}

//Various NON static methods
// use an iterator at one point so they must be NON static

class TimerTaskThread extends TimerTask {
public void run() {
//delete old stuff in _b_dict
}
}
}

//sample usage
public class Main {
public Main() {
A a = new A();
a.contains(new B());
}
}

最佳答案

您是否正在从另一个线程创建另一个 A 实例?因为如果您从同一个线程创建两个实例,那么锁是可重入的,tryLock 显然会返回 true。

如果你真的想从构造函数中调度,而不是从静态 block 中调度,你应该使用静态 AtomicBoolean 变量,并且仅在 compareAndSet(false, true)< 时调度计时器 返回真。

关于java - ReentrantLock.tryLock() 没有锁定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8837494/

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