如何实现优先级线程池队列

首先,我们需要定义一个带优先级的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);
    }
    原文作者:dingpwen
    原文地址: https://blog.csdn.net/dingpwen/article/details/105681288
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞