一步步瞭解執行緒池之自定義-PriorityThreadPool

NiceToMeetYou發表於2019-04-28

特點: 佇列中有優先順序比較的執行緒池

使用案例:

val pool: ExecutorService = ThreadPoolExecutor(
    3, 
    3, 
    0, 
    TimeUnit.SECONDS,
    PriorityBlockingQueue<Runnable>()
)
複製程式碼
暫時先用java寫著
public abstract class PriorityRunnable implements RUnnable, Comparable<PriorityRunnable> {
    private int priority;
    
    public PriorityRunnable(int priority) {
        if (priority < 0) {
            throw new IllegalArgumentException();
        }
        this.priority = priority;
    }
    
    public int getPriority() {
        return priority;
    }
    
    @Override
    public int compareTo(@NonNull PriorityRUnnable another) {
        int me = this.priority;
        int anotherPri = another.getPriority();
        return me == anotherPri ? 0 : me < anotherPri ? 1 : -1;
    }
    
    @override
    public void run() {
        doSomeThing();
    }
    
    protected abstract void doSomeThing();
}
複製程式碼
txt.click {
    for (i in 0..99) {
        val priority = i
        pool.execute(object: PriorityRunnable(priority) {
            override doSomeThing() {
                log("優先順序${proiority}的任務被執行")
                try {
                    Thread.sleep(2000)
                }catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        })
    }
}
複製程式碼

相關文章