如何用固定数目的工作线程实现简单线程

编程入门 行业动态 更新时间:2024-10-22 19:33:39
本文介绍了如何用固定数目的工作线程实现简单线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

更多推荐

如何用固定数目的工作线程实现简单线程

本文发布于:2023-11-26 00:14:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631904.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   目的   如何用   简单   工作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!