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