This question already has an answer here:
ReentrantLock doesn't work out
(1个答案)
2年前关闭。
当我想使用synced关键字或lock更新时,当sum变量为int而不是Integer对象时,它可以工作。
代码看起来像这样-
并且不要忘记在
(1个答案)
2年前关闭。
当我想使用synced关键字或lock更新时,当sum变量为int而不是Integer对象时,它可以工作。
代码看起来像这样-
public class TestSynchronized {
private Integer sum = new Integer(0);
public static void main(String[] args) {
TestSynchronized test = new TestSynchronized();
System.out.println("The sum is :" + test.sum);
}
public TestSynchronized() {
ExecutorService executor = Executors.newFixedThreadPool(1000);
for (int i = 0; i <=2000; i++) {
executor.execute(new SumTask());
}
executor.shutdown();
while(!executor.isTerminated()) {
}
}
class SumTask implements Runnable {
Lock lock = new ReentrantLock();
public void run() {
lock.lock();
int value = sum.intValue() + 1;
sum = new Integer(value);
lock.unlock(); // Release the lock
}
}
}
最佳答案
问题是您为每个locks
对象都单独设置了SumTask
。这些对象应该共享locks
。
在lock
方法中一次创建一个TestSynchronized()
对象。这应该由所有new SumTask(lock)
对象共享。
因此,您的SumTask
类如下所示:
class SumTask implements Runnable {
Lock lock;
public SumTask(Lock commonLock) {
this.lock = commonLock;
}
public void run() {
lock.lock();
int value = sum.intValue() + 1;
sum = new Integer(value);
lock.unlock(); // Release the lock
}
}
并且不要忘记在
commonLock
方法中创建TestSynchronized()
对象: Lock lock = new ReentrantLock();
executor.execute(new SumTask(commonLock));
07-26 08:51