以下代碼應確保跨所有線程同步對「同步」的訪問。跨線程同步
根據a輸出,並非總是如此,請注意Thread-3和Thread-4如何讀取相同的同步值。
我在代碼中丟失了什麼嗎?
[Thread-0] before value of sync is 0
[Thread-0] after value of sync is 1
[Thread-3] before value of sync is 1
[Thread-3] after value of sync is 2
[Thread-4] before value of sync is 1
[Thread-4] after value of sync is 3
[Thread-2] before value of sync is 3
[Thread-2] after value of sync is 4
[Thread-1] before value of sync is 4
[Thread-1] after value of sync is 5
這裏的代碼:
package com.mypackage.sync;
public class LocalSync implements Runnable {
private Integer sync = 0;
public void someMethod() {
synchronized (sync) {
System.out.println("[" + Thread.currentThread().getName() + "]" + " before value of sync is " + sync);
sync++;
System.out.println("[" + Thread.currentThread().getName() + "]" + " after value of sync is " + sync);
}
}
@Override
public void run() {
someMethod();
}
public static void main(String[] args) {
LocalSync localSync = new LocalSync();
Thread[] threads = new Thread[5];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(localSync, "Thread-" + i);
threads[i].start();
}
}
}
同步你知道同步即整數包裝是不可變的? – SMA 2014-11-24 13:06:31