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 的任意排列组合。
