本文介绍了如何使用 Java 5 中的 ExecutorService 实现任务优先级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施一个线程池机制,我想在其中执行不同优先级的任务.我想要一个很好的机制,我可以通过它向服务提交高优先级任务,并在其他任务之前安排它.任务的优先级是任务本身的固有属性(我将该任务表示为 Callable 还是 Runnable 对我来说并不重要).

I am implementing a thread pooling mechanism in which I'd like to execute tasks of varying priorities. I'd like to have a nice mechanism whereby I can submit a high priority task to the service and have it be scheduled before other tasks. The priority of the task is an intrinsic property of the task itself (whether I express that task as a Callable or a Runnable is not important to me).

现在,从表面上看,我可以使用 PriorityBlockingQueue 作为我的 ThreadPoolExecutor 中的任务队列,但该队列包含 Runnable 对象,这可能是也可能不是我提交给它的 Runnable 任务.此外,如果我提交了 Callable 任务,则不清楚这将如何映射.

Now, superficially it looks like I could use a PriorityBlockingQueue as the task queue in my ThreadPoolExecutor, but that queue contains Runnable objects, which may or may not be the Runnable tasks I've submitted to it. Moreover, if I've submitted Callable tasks, it's not clear how this would ever map.

有没有办法做到这一点?我真的不想为此自己动手,因为那样我更有可能弄错.

Is there a way to do this? I'd really rather not roll my own for this, since I'm far more likely to get it wrong that way.

(顺便说一句;是的,我知道在这样的事情中低优先级工作可能会被饿死.对于具有合理公平保证的解决方案的加分(?!))

(An aside; yes, I'm aware of the possibility of starvation for lower-priority jobs in something like this. Extra points (?!) for solutions that have a reasonable guarantee of fairness)

推荐答案

乍一看,您似乎可以为您的任务定义一个接口,扩展 RunnableCallableComparable.然后用一个 PriorityBlockingQueue 包裹一个 ThreadPoolExecutor 作为队列,并且只接受实现你的接口的任务.

At first blush it would seem you could define an interface for your tasks that extends Runnable or Callable<T> and Comparable. Then wrap a ThreadPoolExecutor with a PriorityBlockingQueue as the queue, and only accept tasks that implement your interface.

考虑到您的评论,看起来一种选择是扩展 ThreadPoolExecutor,并覆盖 submit() 方法.参考 AbstractExecutorService 查看默认的样子;他们所做的只是将 RunnableCallable 包装在 FutureTaskexecute() 中.我可能会通过编写一个实现 ExecutorService 并委托给匿名内部 ThreadPoolExecutor 的包装类来做到这一点.将它们包裹在您优先考虑的事情中,以便您的 Comparator 可以得到它.

Taking your comment into account, it looks like one option is to extend ThreadPoolExecutor, and override the submit() methods. Refer to AbstractExecutorService to see what the default ones look like; all they do is wrap the Runnable or Callable in a FutureTask and execute() it. I'd probably do this by writing a wrapper class that implements ExecutorService and delegates to an anonymous inner ThreadPoolExecutor. Wrap them in something that has your priority, so that your Comparator can get at it.

这篇关于如何使用 Java 5 中的 ExecutorService 实现任务优先级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:38