Kotlin CountDownLatch和CyclicBarrier使用方法

在Kotlin中,可以使用CountDownLatch和CyclicBarrier来实现主线程与多个子线程的同步。

复制代码
fun main() {
    val threadCount = 3
    val latch = CountDownLatch(threadCount)

    for (i in 1..threadCount) {
        Thread {
            println("Thread $i is starting")
            Thread.sleep(500)
            latch.countDown()
        }.start()
    }

    latch.await()
    println("All threads have finished")
}

在这个示例中,我们首先创建了一个CountDownLatch实例latch,它的计数器设置为3,表示需要等待3个线程。

然后,我们启动了3个线程,每个线程都会打印两条消息,并调用latch.countDown()。latch.countDown()会减少latch的计数器,当计数器变为0时,主线程会被唤醒并继续执行。

在主线程中,我们调用latch.await(),等待所有线程完成。最后,我们打印一条消息,表示所有线程都已经完成。

下面是一个使用CyclicBarrier的示例:

复制代码
fun main() {
    val threadCount = 3
    val barrier = CyclicBarrier(threadCount)

    for (i in 1..threadCount) {
        Thread {
            println("Thread $i is starting")
            Thread.sleep(500)
            barrier.await()
        }.start()
    }

    barrier.await()
    println("All threads have crossed the barrier")
}

在这个示例中,我们首先创建了一个CyclicBarrier实例barrier,它的计数器设置为3,表示需要等待3个线程。

然后,我们启动了3个线程,每个线程都会打印两条消息,并调用barrier.await()。barrier.await()会等待所有线程到达屏障点,当所有线程都到达屏障点后,barrier会重置,并允许一组新的线程开始等待。

在主线程中,我们调用barrier.await(),等待所有线程到达屏障点。最后,我们打印一条消息,表示所有线程都已经到达屏障点。

相关推荐
pan_junbiao1 小时前
Go 语言基本数据类型
java·前端·golang
敲上瘾4 小时前
Qt 主窗口QMainWindow:菜单栏、工具栏、状态栏与浮动窗口等
开发语言·c++·qt·ui·qt6.3
BK贝壳9 小时前
布尔数组也能做按位取反、移位和乘法:bool-hybrid-array 的位运算在本机跑了一遍
开发语言·数据结构·python·性能优化·numpy
ZhengEnCi9 小时前
前端日志和后端日志怎么记:分级、JSON 格式、按天分文件与保留策略
前端·后端·python
吴名氏.10 小时前
全栈跃迁:Java 后端 27 讲【3】Vue3工程化脚手架
java·开发语言·springboot·全栈工程师
codeejun10 小时前
每日一Go·MySQL-24、死锁排查与解决方案
开发语言·mysql·golang
kyriewen10 小时前
我给 61 个前端库排了两次名,最多差了 46 位
前端·javascript·程序员
亲亲小宝宝鸭10 小时前
Cesium启动:TLE数据是如何变成轨迹线的
前端·cesium
阿里云云原生11 小时前
对话即构建,在 AgentCore 构建 Agent 就是这么简单
前端·agent
夕水11 小时前
我给我的诗写了个后台,顺手写了 一个组件库ew-solid-ui
前端·javascript·typescript