5

In Java is there a way to set the priority for the thread that will be calling the doInBackground() method of a SwingWorker object?

In the Thread API there is a setPriority() method. The SwingWorker.execute() method schedules the swingworker for execution on a worker thread. I would like to have access to that worker thread to set it's priority.

From my understanding this worker thread comes from a default worker thread pool. Would the only way to handle this is to use my own executor?

4

3 回答 3

8

JDK7 SwingWorker javadoc暗示设计者不打算让用户直接与后台线程交互或更改后台线程:

... the exact strategy of choosing a thread for any particular SwingWorker is unspecified and should not be relied on.

SwingWorker.getWorkersExecutorService() 的实现似乎强化了这个想法,因为他们以一种不容易改变的方式实现了它。

SwingWorker 是典型案例的样板解决方案,您没有典型案例。我建议你编写代码来处理运行后台任务,而不是试图破解 SwingWorker 来做你想做的事。这样,将来维护您的代码的任何人(甚至您自己!)都不会想知道为什么 SwingWorker 的行为不符合预期。

于 2012-04-16T18:50:46.567 回答
6

我能想到的唯一方法是让 execute 方法使用Thread.currentThread(). 然后,您可以设置此线程的优先级(前提是允许调用者)。

于 2012-04-16T15:59:37.310 回答
2

由于 SwingWorker 是一个Runnable,您可以将其提交给任何java.util.concurrent.ExecutorService

于 2012-04-16T20:43:37.190 回答