public class VolatileDemo implements Runnable{
private static volatile int count = 0;
private Random random = new Random();
public static void main(String[] args) {
for(int i=0;i<1000;i++){
new Thread(new VolatileDemo()).start();
}
while(Thread.activeCount()>1){
Thread.yield();
}
System.out.println(count);
}
@Override
public synchronized void run() {
try {
Thread.sleep(random.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" " + count++);
}
}
After running (in jdk1.8), the answer is not 1000. Please tell me the reason.