As we all know, i++ is not atomic in java, so I try to write a program to prove that.
My idea is to new several threads and inside each thread, increase count(which is a static field in the Main class).
If
threadNum * iteration > count,
then we can prove i++ is not atomic, but actually I've always got them equal.
Here is my code:
import java.util.ArrayList;
import java.util.List;
public class ConcurrentTest{
private static int count = 0;
public static void main(String[] args) throws Exception{
List<Thread> threads = new ArrayList<>();
for(int i = 0; i<12; ++i){
threads.add(new Thread(() -> {
for(int j=0; j<1000000; ++j) {
count++;
}
}));
}
for(Thread t: threads){
t.start();
t.join();
}
System.out.println(count);
}
}
The result is 12000000.
And no mater how I change i and j in the above program, i*j === count.
I don't know if this is helpful: this program has been tested on JRE 6, 7 and 8. I haven't tested it in Java 5 or earlier.