2013-11-14 18 views
2

我试图编写一个程序来测试在java中执行父/子线程的效果!为什么有效线程的数量低于3?其他线程会发生什么。它让我认为Java可以拥有数百万个线程,但只有少数线程可以处于活动状态。这是正确的还是还有别的?为什么在这个递归线程的例子中活动线程的数量没有通过3?

public class ManyThreadsTester { 
    static int threadCount = 0; 
    static class recursiveRunnable implements Runnable{ 

     @Override 
     public void run() { 
      System.out.println(threadCount); 
      // Arrives up to infinity if the System.exit(0) statement is absent! 
      try { 
       System.out.println("Active threads before: " + Thread.activeCount()); 
       //Always prints 2 
       Thread.sleep(40); 
       threadCount++; 
       new Thread(new recursiveRunnable()).start(); 
      } catch (InterruptedException ex) { 
       Logger.getLogger(ManyThreadsTester.class.getName()).log(Level.SEVERE, null, ex); 
      } 
      System.out.println("Active threads after: " + Thread.activeCount()); 
      //Always prints 3 
     } 


    } 

    public static void main(String... args) throws InterruptedException{ 
     Thread th = new Thread(new recursiveRunnable()); 
     th.start(); 
     Thread.sleep(5000); 
     System.out.print("FINAL ACTIVE THREAD COUNTS: " + Thread.activeCount()); 
     //prints 2 
     System.exit(0); 
    } 
} 
+0

你得到活动线程三个或两个?如果您的标题包含或不包含,但不清楚,但在您的代码中,您似乎写了“打印2”。所以我假设你的意思是它永远不会返回超过2作为活动线程数。这也可能意味着您正在双核机器上运行此代码。请参阅:[多线程,并发线程如何工作?](http://stackoverflow.com/questions/8243682/multi-threading-how-does-concurrent-threads-work) – turbo

+0

@turbo如果您阅读代码注释那么你会发现“主动线程之后:”总是打印3,而“主动线程之前:”总是打印2!所以它永远不会传递3! – Johnny

+0

啊我错过了,我的错误 – turbo

回答

3

因为你在产卵后立即退出子线程。如果你在最后添加的延迟,你会得到更高的数字:

new Thread(new recursiveRunnable()).start(); 
Thread.sleep(10000); 

输出:

... 
Active threads before: 30 
28 
Active threads before: 31 
29 
Active threads before: 32 
30 
... 
+0

Ja!这就是问题所在。但是现在我想知道java如何管理所有这些线程。改变我可以达到50,000个活跃线程的数字(也许更多)!它可能会导致真实世界的编程中显着的饥饿。 – Johnny

+1

并发线程数量对JVM来说是一个严重的问题。为了避免这种情况,可以将数据分批整理并提交给线程池。线程池限制活动线程的数量并将其重用于提交的作业。 –

相关问题