How do I implement task prioritization using an ExecutorService in Java 5?

前端 未结 6 1928
粉色の甜心
粉色の甜心 2020-11-27 03:51

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 prior

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 04:08

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

    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.

提交回复
热议问题