如何实现ExecutorService以轮换为基础执行任务? [英] How to implement an ExecutorService to execute tasks on a rotation-basis?

查看:101
本文介绍了如何实现ExecutorService以轮换为基础执行任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 java.util。 concurrent.ExecutorService with 修复线程池以执行任务列表。我的任务列表通常在80到150左右,我将任何时候运行的线程数限制为10,如下所示:

  ExecutorService threadPoolService = Executors.newFixedThreadPool(10); 

for(Runnable task:myTasks)
{
threadPoolService.submit(task);
}

我的用例要求即使完成的任务也应该重新提交给 ExecutorService 但只有在所有已经提交的任务都得到服务/完成时才应该执行/重新执行。基本上,提交的任务应该以轮换方式执行。因此,在这种情况下,将不会有 threadPoolService.shutdown() threadPoolService.shutdownNow()调用。 / p>

我的问题是,如何实现 ExecutorService 服务轮换基础任务?

解决方案

ThreadPoolExecutor为afterExecution提供了一个扩展点,您可以将作业放回队列末尾。

  public class TaskRepeatingThreadPoolExecutor extends ThreadPoolExecutor {

public TaskRepeatingThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,BlockingQueue< Runnable> workQueue){
super(corePoolSize, maximumPoolSize,keepAliveTime,unit,workQueue);
}

@Override
protected void afterExecute(Runnable r,Throwable t){
super.afterExecute(r,t);
this.submit(r);
}
}

你需要做更多的工作当然要在没有 ExecutorService 的方便的工厂方法的帮助下自己实例化它,但构造函数很简单,可以理解。


I'm using java.util.concurrent.ExecutorService with fixed thread pool to execute list of tasks. My list of tasks will typically be around 80 - 150 and I've limited the number of threads running at any time to 10 as shown below:

ExecutorService threadPoolService = Executors.newFixedThreadPool(10);

for ( Runnable task : myTasks ) 
{     
    threadPoolService.submit(task); 
}

My use case demands that even the completed task should be re-submitted again to the ExecutorService but it should be executed/taken again only when all the already submitted tasks are serviced/completed. That is basically, the tasks submitted should be executed on a rotation-basis. Hence, there will not be either threadPoolService.shutdown() or threadPoolService.shutdownNow() call in this case.

My question is, how do I implement ExecutorService servicing rotation-basis tasks?

解决方案

ThreadPoolExecutor provides an extension point for afterExecution where you can put the job back at the end of the queue.

public class TaskRepeatingThreadPoolExecutor extends ThreadPoolExecutor {

    public TaskRepeatingThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        this.submit(r);
    }
}

You'll have to do a little more work of course to instantiate it yourself without the help of ExecutorService's handy factory method, but the constructors are simple enough to grok.

这篇关于如何实现ExecutorService以轮换为基础执行任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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