在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(),等待所有线程到达屏障点。最后,我们打印一条消息,表示所有线程都已经到达屏障点。