简体   繁体   English

如何启动和管理Java线程?

[英]How to start and manage Java threads?

The following code works, fine, but i wonder .. conceptually, is it correct? 以下代码工作正常,但我想知道..从概念上讲,它是否正确? Start the threads, wait for them to join . 启动线程,等待它们join Should ThreadPool be used instead? 应该使用ThreadPool吗?

If possible, please comment 如果可能,请发表评论

List<Thread> threads = new ArrayList<Thread>();

for (Test test : testsToBeExecuted) {
  Thread t = new Thread(test);
  threads.add(t);
  t.start();
}

for (Thread thread : threads) {
  thread.join();
}

Conceptually it looks fine. 从概念上讲,它看起来很好 You can use an ExecutorService which you create one like: 您可以使用您创建的ExecutorService,如:

ExecutorService service = Executors.newFixedThreadPool(testsToBeExecuted.size());

Thenyou would create a list of Callables and invokeAll on the executor service itself. Thenyou会在执行程序服务本身上创建一个Callables列表和invokeAll。 That in essence will do the same thing. 这本质上也会做同样的事情。

Agree that ExecutorService is the way to go. 同意ExecutorService是要走的路。 I have a utility class that uses ExecutorService to run a arbitrary number of tasks, collect the results and return them as a list. 我有一个实用程序类,它使用ExecutorService来运行任意数量的任务,收集结果并将它们作为列表返回。 ExecutorService will do all of the housekeeping for you. ExecutorService将为您完成所有的清洁工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM