我试图编写一个程序来测试在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);
}
}
你得到活动线程三个或两个?如果您的标题包含或不包含,但不清楚,但在您的代码中,您似乎写了“打印2”。所以我假设你的意思是它永远不会返回超过2作为活动线程数。这也可能意味着您正在双核机器上运行此代码。请参阅:[多线程,并发线程如何工作?](http://stackoverflow.com/questions/8243682/multi-threading-how-does-concurrent-threads-work) – turbo
@turbo如果您阅读代码注释那么你会发现“主动线程之后:”总是打印3,而“主动线程之前:”总是打印2!所以它永远不会传递3! – Johnny
啊我错过了,我的错误 – turbo