一步步瞭解執行緒池之單核執行緒池-SingleThreadPool

NiceToMeetYou發表於2019-04-28

SingleThreadPool構造方法

public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService(
                new ThreadPoolExecutor(1, 
                1, 
                0L, 
                TimeUnit.MILLISECONDS, 
                new LinkedBlockingQueue<Runnable>()));
}
複製程式碼

特點: 單個後臺執行緒(其緩衝佇列無界)。單執行緒序列執行所有任務。

使用案例:

val pool: ExecutorService = Executors.newSingleThreadExecutor()

複製程式碼
txt.click {
    for (i in 0 until 30) {
        val runnable = Runnable {
            try {
                Thread.sleep(2000)
                log("當前執行緒是:", Thread.currentThread.name)
            }catch(e: Exception) {
                e.printStackTrace()
            }
        }
        pool.execute(runnable)
    }
}
複製程式碼

相關文章