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)
}
}
复制代码