while(Thread.activeCount() > 1) 所有子線程執行完還是大於1


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();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM