我想我只是沒有看到一些東西,因爲我已經得到了這個工作在過去。ReentrantLock.tryLock()沒有鎖定
我的鎖沒有持有獨佔鎖,並且當創建對象的新實例時,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());
}
}
爲什麼你需要一個鎖?爲什麼不在靜態塊中初始化靜態值?我看不到它會創建第二個任務。 – 2012-01-12 15:25:56
它真的看起來像那樣嗎?你永遠不會用'clean_lock.unlock()'釋放鎖嗎? – 2012-01-12 15:26:15
@JohnVint我相信這是它只能創造一個任務。 – 2012-01-12 15:27:21