一步步瞭解執行緒池之按需建立-CachedThreadPool

NiceToMeetYou發表於2019-04-28

CachedThreadPool構造方法

public static ExecutorService newCachedThreadPooll() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
}
複製程式碼

該執行緒池特點:無核心執行緒數,只有非核心執行緒,非核心執行緒數可達到Integer.MAX_VALUE,且非核心執行緒等待時間為60秒,採用SynchronousQueue佇列。

使用案例:

val pool: ExecutorService = Executors.newCachedThreadPool()

複製程式碼
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)
    }
}
複製程式碼

相關文章