【问题标题】:ThreadPoolExecutor and Android's thread priorityThreadPoolExecutor 和 Android 的线程优先级
【发布时间】:2014-01-17 12:59:24
【问题描述】:

我想创建一个 ThreadPollExecutor 来执行具有给定优先级 Process.setThreadPriority(int) 的任务。

我该怎么做?在发送到线程轮询的每个可运行的开始时添加对 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();
        }

    }

}

这个问题的最佳解决方案是什么?谢谢

【问题讨论】:

    标签: java android multithreading parallel-processing


    【解决方案1】:

    您问题中给出的自定义工厂是执行此操作的正确方法。正是出于这个原因使用了工厂模式,因为它使您可以完全控制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;
        }
    
    }
    

    【讨论】:

    • 好的,我对多线程不是很有经验,需要确认,非常感谢
    • 你的工厂似乎比需要的复杂一些,我会发布一个简化版本。
    • @TimB 这里 Prority 应该从 andorid.os.Process 类还是 Java Thread 类中设置?因为两者的优先级顺序相反。
    • 是的,我可以看到。所以我在 Android 中使用这个类,那么我应该使用哪个优先级?
    • 阅读文档以了解您正在使用的内容,我希望它是 java 的,但如果您不确定,请尝试并检查。 ..
    猜你喜欢
    • 2012-11-17
    • 2023-04-06
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    相关资源
    最近更新 更多