我需要以较低优先级(ScheduledExecutorService
)运行MIN_PRIORITY
执行的所有计划任务/线程,而不是应用程序中的所有其他线程。我一直这样做,但这是完成这个的正确方法吗?
ScheduledExecutorService schdExctr = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
});
我认为更好的实施方式是:
private ScheduledExecutorService schdExctr = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
});
答案 0 :(得分:2)
是的,这是正确的方法,另外你可以查看Executors.DefaultThreadFactory
类源来查看默认线程的命名方式。
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.MIN_PRIORITY)
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
其中group
和namePrefix
是:
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
和threadNumber
是:
private final AtomicInteger threadNumber = new AtomicInteger(1);.
在您的实施中,您将不需要poolNumber
。
编辑问题后编辑: 解决方案是:
private ScheduledExecutorService schdExctr = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
private ThreadFactory defaultThreadFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable r) {
Thread t = defaultThreadFactory.newThread(r);
t.setPriority(Thread.MIN_PRIORITY);
return t;
}
});