1 回答

TA贡献1805条经验 获得超9个赞
有点傻自己。
它就是这样工作的,因为我实际上锁定了不同的对象。
private static synchronized int getCount()
等于
private static synchronized (ReentrantLockZero.class) int getCount()
而始终是一个新对象,并且无法使用不同的锁来消除争用条件。new ReentrantLock();
所以傻瓜我,它很容易通过以下演示修复
public class ReentrantLockZero {
private static ReentrantLock CountLock = new ReentrantLock();
private static int synchronisedCount = 0;
private static int lockedCount = 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::getSynchronisedCount);
threadPoolExecutor.submit(ReentrantLockZero::getCountUsingLock);
}
threadPoolExecutor.shutdown();
threadPoolExecutor.awaitTermination(10, TimeUnit.SECONDS);
assert synchronisedCount == RESULT_COUNT;
assert lockedCount == RESULT_COUNT;
}
private static synchronized int getSynchronisedCount() {
synchronisedCount++;
System.out.println(Thread.currentThread().getName() + " counting in synchronized: " + synchronisedCount);
return synchronisedCount;
}
private static int getCountUsingLock() {
CountLock.lock();
try {
lockedCount++;
System.out.println(Thread.currentThread().getName() + " counting in lock: " + lockedCount);
return lockedCount;
} finally {
CountLock.unlock();
}
}
}
为什么工作?因为那时只有一个锁,所以两种方法都锁定了,所以直接解决了争用条件。synchronized
添加回答
举报