Given the code fragments:



class MyThread implements Runnable {

    private static AtomicInteger count = new AtomicInteger(0);

    public void run() {
        int x = count.incrementAndGet();
        System.out.print(x + " ");
    }
}

and

Thread thread1 = new Thread(new MyThread());
Thread thread2 = new Thread(new MyThread());
Thread thread3 = new Thread(new MyThread());
Thread[] ta = {thread1, thread2, thread3};
for (int x = 0; x < 3; x++) {
    ta[x].start();
}

Which statement is true?

A. The program prints 1 2 3 and the order is unpredictable.
B. The program prints 1 2 3.
C. The program prints 1 1 1.
D. A compilation error occurs.

題解

AtomicInteger的incrementAndGet方法,可以使AtomicInteger所表示的整數值加一後,同時回傳整數結果,在操作AtomicInteger物件的數值時,同一時間永遠只有一個執行緒可以存取,所以可以達成thread-safe。

程式第8行的x區域變數,在每個執行緒中的數值都不一樣,排序後為1、2、3。但是執行緒執行第9行的順序不同,因此輸出結果會是1、2、3的任意排列組合。