8

Possible Duplicate:
Java Executors: how can I set task priority?

I have a ThreadPoolExecutor built using a LinkedBlockingDequeue and I want to manipulate the underlying queue, however reading this in the documentation makes me very nervous.

Queue maintenance

Method getQueue() allows access to the work queue for purposes of monitoring and debugging. Use of this method for any other purpose is strongly discouraged. Two supplied methods, remove(java.lang.Runnable) and purge() are available to assist in storage reclamation when large numbers of queued tasks become cancelled.

Specifically I want to be able to

  1. Check the queue to see if an element already exists. I assume this is fine as no locking should be necessary to just view the elements in the queue.
  2. I want to reorder the queue based on some signal. This can obviously be troublesome. I was wondering if there is a preferred way to do this so that I won't mess up the queue for other uses.

Thanks

4

1 回答 1

4

getQueue()将始终返回BlockingQueue<Runnable>您传递给ThreadPoolExecutor.

文档担心的是,如果您不能保证BlockingQueue. 如果您使用PriorityBlockingQueue, 并且只使用removeand add(或者,更直接地,offer),那么您将是安全的,您甚至可以直接从getQueue().

换句话说,每当您的信号告诉您 someRunnable的优先级已更改时,您就应该remove检查删除的结果(true如果已删除),并且只有当它实际上已被删除时,您才应重新添加它。您不能保证在这些操作之间不会拾取某些东西,但至少可以保证您不会重复运行,如果使用-> ->Runnable完成,这很容易发生。containsremoveadd

要么这样,要么您可以编写自己的 a 实现,该实现BlockingQueue使用 a Comparator(如PriorityBlockingQueue),在要求新数据时找到最高优先级。考虑到所涉及的各种接口,这听起来需要做更多的工作。

于 2012-09-20T18:33:21.887 回答