3

我需要以低于应用程序中所有其他线程的ScheduledExecutorService优先级(at )运行所有计划任务/线程。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;
                                            }
                                        });
4

1 回答 1

3

是的,这是正确的方法,另外您可以查看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;
        }
    });
于 2013-09-21T19:36:52.033 回答