我想實現一個計數器使用原子整數,然後在所有線程完成其任務後,打印最終值,但我沒有得到最新值,在我的情況下,我應該的價值獲得應該是20,但它是波動像17,18,16,19,20等原子整數增量程序不按預期工作
程序如下:
class AtomicOperations implements Runnable
{
private AtomicInteger ai;
private int a;
AtomicOperations(int aivalue, int ivalue) {
ai = new AtomicInteger(aivalue);
this.a = ivalue;
}
@Override
public void run() {
ai.getAndIncrement();
}
public static void main(String args[]) {
AtomicOperations obj = new AtomicOperations(10, 10);
Thread[] t = new Thread[10];
synchronized (obj) {
for (int i = 0; i < t.length; i++) {
t[i] = new Thread(obj, "Thread-" + (i + 1));
t[i].start();
}
}
System.out.println(obj.ai);
}
}
你覺得你的'synchronized(obj)'有什麼好處? – Kayaman
原子不需要同步。 –
@Kayaman ..我認爲這可能會完成打印語句運行之前的所有線程 – Amol