Java:如何获取完成的线程以从运行线程中提取任务 [英] Java: How to get finished threads to pickup tasks from running threads

查看:249
本文介绍了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与其他类型的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.

看看这个

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

看看其他相关的Java并发API @ 教程例如ThreadPoolExecutorExecutorService

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

这篇关于Java:如何获取完成的线程以从运行线程中提取任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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