当我想使用 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
}
}
}
四季花海
相关分类