Kotlin Executors线程池newSingleThreadExecutor单线程

本文通过Kotlin的Executors.newSingleThreadExecutor实现单线程任务执行,并与JavaExecutorService进行对比,展示了如何创建和使用线程池。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Kotlin Executors线程池newSingleThreadExecutor单线程

 

import java.util.concurrent.Executors

fun main() {
    val mExecutorService = Executors.newSingleThreadExecutor()

    for (i in 1..5) {
        mExecutorService.execute {
            println("seq-$i tid:${Thread.currentThread().threadId()} ->start")
            Thread.sleep(1000)
            println("seq-$i tid:${Thread.currentThread().threadId()} <-end")
        }
    }

    mExecutorService.shutdown()
}

seq-1 tid:22 ->start
seq-1 tid:22 <-end
seq-2 tid:22 ->start
seq-2 tid:22 <-end
seq-3 tid:22 ->start
seq-3 tid:22 <-end
seq-4 tid:22 ->start
seq-4 tid:22 <-end
seq-5 tid:22 ->start
seq-5 tid:22 <-end

Process finished with exit code 0

 

 

Java线程池:ExecutorService,Executors_executorservice线程池_zhangphil的博客-CSDN博客简单的Java线程池可以从Executors.newFixedThreadPool( int n)获得。此方法返回一个线程容量为n的线程池。然后ExecutorService的execute执行之。现给出一个示例。package zhangphil.executorservice;import java.util.concurrent.ExecutorService;import j_executorservice线程池https://blog.csdn.net/zhangphil/article/details/43898637ScheduledThreadPoolExecutor周期性执行线程任务scheduleAtFixedRate_zhangphil的博客-CSDN博客ScheduledThreadPoolExecutor周期性执行线程任务scheduleAtFixedRate ScheduledThreadPoolExecutor mScheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1); mScheduledThreadPoolExecutor.sched...https://blog.csdn.net/zhangphil/article/details/80735215

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值