ScheduledExecutorService以低于其他应用程序中所有其他线程的优先级运行所有计划任务

时间:2013-09-21 19:31:31

标签: java multithreading

我需要以较低优先级(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;
                                            }
                                        });

1 个答案:

答案 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;
    }

其中groupnamePrefix是:

        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;
        }
    });