1.發現了一個問題 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);
}
}
2.陷入了死循環.......why?
Thread.yield();//應該主線程先讓出cpu使用權
問題在這Thread.activeCount() 還有個守護線程!!!所以就會一直陷入無限循環。
加了一句Thread.currentThread().getThreadGroup().list();
while (Thread.activeCount() > 1) {
Thread.currentThread().getThreadGroup().list();
Thread.yield();
}