@jeshurun 的答案是正确的,但为了后代,我想我会添加更多信息。如果您使用出色的ExecutorService
代码,那么您的代码将变成:
ExecutorService threadPool = Executors.newFixedThreadPool(10);
while (moreWork) {
threadPool.submit(new MyClass);
}
// stop pool after you've submitted the last job, submitted jobs will still run
threadPool.shutdown();
// you can wait for the last job to finish if you'd like
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
您MyClass
应该实施Runnable
或Callable
. 如果是a,Runnable
那么线程池将MyClass.run()
在它有可用线程时执行该方法。除了方法返回的值可以用来获取你的方法返回的值Callable
之外,与此相同。您还可以获得由. 这是一个不错的教程。Future<?>
submit()
MyClass.call()
call()