使用ExecutorService控制任务执行顺序 [英] Controlling Task execution order with ExecutorService

查看:852
本文介绍了使用ExecutorService控制任务执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个进程将异步任务委托给线程池。我需要确保某些任务按顺序执行。
例如

I have a process which delegates asynch tasks to a pool of threads. I need to ensure that certain tasks are executed in order. So for example

任务按顺序到达

任务a1,b1,c1,d1, e1,a2,a3,b2,f1

Tasks a1, b1, c1, d1 , e1, a2, a3, b2, f1

任务可以以任何顺序执行,除非有自然依赖性,所以a1,a2,a3必须在

Tasks can be executed in any order except where there is a natural dependancy, so a1,a2,a3 must be processed in that order by either allocating to the same thread or blocking these until I know the previous a# task was completed.

目前它不使用Java并发软件包,但我'

Currently it doesn't use the Java Concurrency package, but I'm considering changing to take avantage of the thread management.

有没有人有类似的解决方案或建议如何实现这

Does anyone have a similar solution or suggestions of how to achieve this

推荐答案

当我这样做过去,我通常有一个组件,然后提交callables / runnables到执行器的处理。

When I've done this in the past I've usually had the ordering handled by a component which then submits callables/runnables to an Executor.

有类似的东西。


  • 有运行的任务列表,有些包含依赖关系

  • 使用ExecutorCompletionService创建执行器和换行

  • 搜索所有没有依赖关系的任务,通过完成服务计划

  • 轮询完成服务

  • 随着每个任务完成


    • 将其添加到完成列表

    • 重新评估任何等待任务wrt到完成列表,看看他们是否依赖完成。

    • Got a list of tasks to run, some with dependencies
    • Create an Executor and wrap with an ExecutorCompletionService
    • Search all tasks, any with no dependencies, schedule them via the completion service
    • Poll the completion service
    • As each task completes
      • Add it to a "completed" list
      • Reevaluate any waiting tasks wrt to the "completed list" to see if they are "dependency complete". If so schedule them
      • Rinse repeat until all tasks are submitted/completed

      完成服务是一个很好的方法,能够获得任务,因为他们完成,而不是试图调查一堆期货。但是,您可能希望保留一个 Map ,当任务通过完成服务计划时填充,以便当完成服务给您一个完整的未来你可以知道 TaskIdentifier 是什么。

      The completion service is a nice way of being able to get the tasks as they complete rather than trying to poll a bunch of Futures. However you will probably want to keep a Map<Future, TaskIdentifier> which is populated when a task is schedule via the completion service so that when the completion service gives you a completed Future you can figure out which TaskIdentifier it is.

      如果你发现自己处于任务仍在等待的状态运行,但没有任何正在运行,没有可以安排,那么你有一个循环依赖的问题。

      If you ever find yourself in a state where tasks are still waiting to run, but nothing is running and nothing can be scheduled then your have a circular dependency problem.

      这篇关于使用ExecutorService控制任务执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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