Java:如何获取完成的线程以从运行线程中提取任务

编程入门 行业动态 更新时间:2024-10-25 16:21:52
本文介绍了Java:如何获取完成的线程以从运行线程中提取任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在处理具有不同运行时间的任务的多线程应用程序.当一个线程结束时,是否有办法从仍在运行的线程中接管一些任务?

I am working on a multithreaded application with tasks that have varying run times. When one thread finishes, is there a way for it to take over some tasks from a still running thread?

这里是一个例子.我从5个线程开始我的程序,每个线程有50个任务.当运行速度最快的线程完成时,另一个线程仍然有40个任务要完成.我如何才能从另一个线程中获取完成的线程来执行20个任务,因此每个线程继续执行20个任务,而不是等待正在运行的线程完成剩余的40个任务?

Here is an example. I kick off my program with 5 threads, and each have 50 tasks. When the quickest running thread finishes, another thread still has 40 tasks to complete. How can I get the finished thread to take 20 tasks from the other thread, so each continue working on 20 a piece, rather than waiting for the running thread to complete the remaining 40?

推荐答案

使用 ForkJoinPool

ForkJoinPool与其他类型的ExecutorService的不同之处主要在于采用了工作窃取:池中的所有线程都试图查找并执行由其他活动任务创建的子任务(如果不存在,则最终阻塞等待工作).当大多数任务派生其他子任务时(这与大多数ForkJoinTasks一样),这可以实现高效处理.在构造函数中将asyncMode设置为true时,ForkJoinPools也可能适用于从未加入的事件样式任务.

A ForkJoinPool differs from other kinds of ExecutorService mainly by virtue of employing work-stealing: all threads in the pool attempt to find and execute subtasks created by other active tasks (eventually blocking waiting for work if none exist). This enables efficient processing when most tasks spawn other subtasks (as do most ForkJoinTasks). When setting asyncMode to true in constructors, ForkJoinPools may also be appropriate for use with event-style tasks that are never joined.

Java 8在执行程序中提供了另外一个API

Java 8 provides one more API in Executors

static ExecutorService newWorkStealingPool()

使用所有可用处理器作为目标并行度级别来创建窃取线程的池.

Creates a work-stealing thread pool using all available processors as its target parallelism level.

看看这个Ilya Grigorik的noreferrer> igvtia文章.

Have a look at this igvtia article by Ilya Grigorik for more details.

看看其他相关的Java并发API @ 教程例如ThreadPoolExecutor,ExecutorService等

Have a look at other related java concurrent API @ tutorials like ThreadPoolExecutor, ExecutorService etc.

更多推荐

Java:如何获取完成的线程以从运行线程中提取任务

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

发布评论

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

>www.elefans.com

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