當我想使用 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
提交
取消