package synchronize;
public class VolatileDemo {
private volatile int number = 0;
public int getNumber() {
return this.number;
}
public void increase() {
this.number++;
}
public static void main(String[] args) {
final VolatileDemo vd = new VolatileDemo();
for (int i = 0; i < 500; i++) {
new Thread(() -> vd.increase()).start();
}
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println("number is " + vd.getNumber());
}
}这个代码在idea里面启动了以后,一直不结束是为什么?
改成 > 2,就可以返回了
idea中Thread.activeCount()返回的是2,是因为多了个monitor ctrlbreak线程。
可参考 http://blog.csdn.net/xiaolinzi007/article/details/44487851
在while循环中打印出Thread.activeCount()的数量,并输出运行的线程名称,确认一下除了主线程外还有哪个线程在执行。