gpt4 book ai didi

java - ThreadPoolExecutor与Android的线程优先级

转载 作者:太空狗 更新时间:2023-10-29 16:18:39 25 4
gpt4 key购买 nike

我想制作一个 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();
}

}

}

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

最佳答案

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

}

关于java - ThreadPoolExecutor与Android的线程优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21186645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com