首先,我们需要定义一个带优先级的Runnable:
/**
* to use PriorityBlockingQueue, we need PriorityRunnable threads
*/
public abstract class PriorityRunnable implements Runnable, Comparable<PriorityRunnable> {
private int priority;
private PriorityRunnable(int priority) {
if (priority < 0) {
throw new IllegalArgumentException();
}
this.priority = priority;
}
@Override
public int compareTo(PriorityRunnable another) {
return another.getPriority() - priority;
}
private int getPriority() {
return priority;
}
}
然后定义线程池的时候使用PriorityBlockingQueue:
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT << 1 + 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
@Override
public Thread newThread(@NonNull Runnable r) {
return new Thread(r, "SpeechManager#" + mCount.getAndIncrement());
}
};
private static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE,
0, TimeUnit.SECONDS, new PriorityBlockingQueue<Runnable>(), sThreadFactory);
然后放入线程池的线程应该是PriorityRunnable的实现,而不是Runnable:
public void speech(final String content, int priority) {
Runnable speechTask = new PriorityRunnable(priority) {
@Override
public void run() {
for (int i = mSpeeches.size() -1; i >= 0; i--) {
ISpeech speech = mSpeeches.valueAt(i);
if (speech != null && speech.isInit() && !TextUtils.isEmpty(content)) {
if(speech.startSpeech(content, false)) break;
}
}
}
};
THREAD_POOL_EXECUTOR.execute(speechTask);
}