如何用固定数目的工作线程实现简单线程 [英] How to implement simple threading with a fixed number of worker threads

查看:109
本文介绍了如何用固定数目的工作线程实现简单线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找最简单,最直接的方法来实现以下操作:

I'm looking for the simplest, most straightforward way to implement the following:


  • 主程序实例化worker

  • 只需 n 个任务可以一次运行。

  • 当到达 n 时,在运行线程的
    的计数回落到 n c $ c>。

  • 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.

这篇关于如何用固定数目的工作线程实现简单线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆