我正在寻找最简单,最直接的方法来实现以下操作:
I'm looking for the simplest, most straightforward way to implement the following:
- 主程序实例化worker
- 只需 n 个任务可以一次运行。
- 当到达 n 时,在运行线程的的计数回落到 n 。
- The main program instantiates worker threads to do a task.
- Only n tasks can be running at once.
- When n is reached, no more workers are started until the count of running threads drops back below n.
我认为 Executors.newFixedThreadPool 符合您的要求。有多种不同的方法来使用生成的ExecutorService,这取决于您是否希望将结果返回到主线程,或者任务是否完全自包含,以及是否有要执行的任务的集合,任务是否排队以响应某些事件。
I think that Executors.newFixedThreadPool fits your requirements. There are a number of different ways to use the resulting ExecutorService, depending on whether you want a result returned to the main thread, or whether the task is totally self-contained, and whether you have a collection of tasks to perform up front, or whether tasks are queued in response to some event.
Collection<YourTask> tasks = new ArrayList<YourTask>(); YourTask yt1 = new YourTask(); ... tasks.add(yt1); ... ExecutorService exec = Executors.newFixedThreadPool(5); List<Future<YourResultType>> results = exec.invokeAll(tasks);或者,如果您有一个新的异步任务来响应某个事件,使用ExecutorService的简单 execute(Runnable)方法。
Alternatively, if you have a new asynchronous task to perform in response to some event, you probably just want to use the ExecutorService's simple execute(Runnable) method.
更多推荐
如何用固定数目的工作线程实现简单线程
发布评论