我想创建一个ThreadPollExecutor来执行具有给定优先级Process.setThreadPriority(int)的任务。
我该怎么办?在发送给线程轮询的每个runnable的开头添加对setThreadPriority的调用?我也考虑使用这样的自定义线程工厂:
private final static class ProcessPriorityThreadFactory implements ThreadFactory {
private final int threadPriority;
public ProcessPriorityThreadFactory(int threadPriority) {
super();
this.threadPriority = threadPriority;
}
@Override
public Thread newThread(Runnable r) {
return new Thread(new PriorityChangeWrapper(r, threadPriority));
}
private final static class PriorityChangeWrapper implements Runnable {
private final Runnable originalRunnable;
private final int threadPriority;
public PriorityChangeWrapper(Runnable originalRunnable, int threadPriority) {
super();
this.originalRunnable = originalRunnable;
this.threadPriority = threadPriority;
}
@Override
public void run() {
Process.setThreadPriority(threadPriority);
originalRunnable.run();
}
}
}
这个问题的最佳解决方案是什么?感谢
答案 0 :(得分:6)
问题中给出的自定义工厂是正确的方法。工厂模式仅用于此原因,因为它可以完全控制ExecutorService
创建的所有线程。 (例如,您也可以更改线程名称等。)
您对工厂的实施要比现在要复杂得多,您只需要:
private final static class ProcessPriorityThreadFactory implements ThreadFactory {
private final int threadPriority;
public ProcessPriorityThreadFactory(int threadPriority) {
this.threadPriority = threadPriority;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setPriority(threadPriority);
return thread;
}
}