今天看到深入理解JVM第367页多线程volatile部分照着书本敲着代码发现了一个问题 Thread.activeCount()会一直大于2
public class VolatileTest {
public static volatile int race = 0;
public static void increase() {
race++;
}
private static final int THREADS_COUNT = 20;
public static void main(String[] args) {
Thread[] threads = new Thread[THREADS_COUNT];
for (int i = 0; i < THREADS_COUNT; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
increase();
}
}
});
threads[i].start();
}
while (Thread.activeCount() > 1) {
Thread.yield();
}
System.out.println(race);
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Bgex3Edw-1603163496497)(https://i.imgur.com/2yGJ4JE.png)]
陷入了死循环…why?
Thread.yield();//应该主线程先让出cpu使用权
问题在这Thread.activeCount() 还有个守护线程!!!所以就会一直陷入无限循环。
加了一句Thread.currentThread().getThreadGroup().list();
while (Thread.activeCount() > 1) {
Thread.currentThread().getThreadGroup().list();
Thread.yield();
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UVU91Zl1-1603163496499)(https://i.imgur.com/RcFOobv.png)]