【发布时间】:2019-03-30 05:03:54
【问题描述】:
我正在尝试遵循ReentrantLock Example in Java, Difference between synchronized vs ReentrantLock 类型的教程。我有一个以-ea 开头的演示
public class ReentrantLockZero {
private static ReentrantLock CountLock = new ReentrantLock();
private static int count = 0;
private static final int RESULT_COUNT = 10_000;
public static void main(String... args) throws Exception {
ThreadPoolExecutor threadPoolExecutor = getMyCachedThreadPool();
for (int i = 0; i < RESULT_COUNT; ++i) {
threadPoolExecutor.submit(ReentrantLockZero::getCount);
threadPoolExecutor.submit(ReentrantLockZero::getCountUsingLock);
}
threadPoolExecutor.shutdown();
threadPoolExecutor.awaitTermination(10, TimeUnit.SECONDS);
assert count == RESULT_COUNT * 2;
}
private static synchronized int getCount() {
count++;
System.out.println(Thread.currentThread().getName() + " counting in synchronized: " + count);
return count;
}
private static int getCountUsingLock() {
CountLock.lock();
try {
count++;
System.out.println(Thread.currentThread().getName() + " counting in lock: " + count);
return count;
} finally {
CountLock.unlock();
}
}
}
当使用ReentrantLock 作为第二种方法getCountUsingLock 时,我会得到java.lang.AssertionError,但是当我将它们注释掉以使用synchronized 时,就可以了。
考虑到它的ReentrantLock,我删除了类中定义的CountLock,并使用如下本地锁,但它仍然不起作用。
private static int getCountUsingLock() {
ReentrantLock countLock = new ReentrantLock();
countLock.lock();
try {
count++;
System.out.println(Thread.currentThread().getName() + " counting in lock: " + count);
return count;
} finally {
countLock.unlock();
}
}
这里遗漏了什么?
任何帮助将不胜感激;)
【问题讨论】:
标签: java java-8 synchronized reentrantlock