当我想使用 synchronized 关键字或锁进行更新时,它在 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 } }}
1 回答
四季花海
TA贡献1811条经验 获得超5个赞
问题是您已将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));
添加回答
举报
0/150
提交
取消