对于这个问题其实在准备面试过程中的一个想法,所以在网上查阅了一下,随后进行尝试,结果是对于否定的,它们不具备原子性。
public class TestAtomicity extends Thread {
static int count = 0;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
count++;
}
}
public static void manyTimesTest() throws InterruptedException {
TestAtomicity testAtomicity = new TestAtomicity();
ExecutorService threadPool = Executors.newFixedThreadPool(1000);
for (int i = 0; i < 1000; i++) {
threadPool.execute(testAtomicity);
}
System.out.println(count);
count = 0;
}
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 10; i++) {
manyTimesTest();
Thread.sleep(1000);
}
}
}
执行结果如下
理论上的结果是100*1000=100000