Reputation: 53
import java.util.concurrent.atomic.AtomicInteger;
public class Volatiletest extends Thread {
private static AtomicInteger atomic = new AtomicInteger(0);
public void run() {
atomic.getAndIncrement();
}
public static void main(String[] args) {
Thread threads[] = new Thread[100];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Volatiletest();
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
System.out.println(atomic.get());
}
}
The code is as above. I think the output is 100, however, the output is random such as 99, 98, 100... Can somebody explain this ?
Upvotes: 1
Views: 70
Reputation: 3339
You are getting different count as your print statement is getting executed before all the threads complete or even start.
You need to call join on all the threads to make the main thread wait until they finish.
// Spawn all threads
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
// Wait for each thread to finish
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
System.out.println(atomic.get());
Upvotes: 2
Reputation: 23567
You're not waiting for the threads to return before printing the result. Thus, you have no guarantee that all of the increment operations have happened before the call to System.out.println()
.
Upvotes: 4