CountDownLatch,Semaphore,CyclicBarrier使用案例

CountDownLatch是Java中的一个同步辅助工具类,它可以让一个或多个线程等待其他线程完成操作后再继续执行。CountDownLatch通过一个计数器来实现,计数器的初始值可以指定,当计数器的值变为0时,所有等待的线程就会被唤醒继续执行。

通常用于以下两种场景:一个线程等待多个其他线程执行完毕后再继续执行; 多个线程等待某个共同事件的发生后再继续执行。

CountDownLatch

  案例一


/**
 * CountDownLatch使用案例,配合await()方法使用,线程执行完毕会阻塞在await()这,直至所有线程执行完毕
 */
public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int numThreads = 3;
        CountDownLatch latch = new CountDownLatch(numThreads);

        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(new Worker(latch));
            thread.start();
        }

        latch.await(); // 主线程等待所有子线程完成任务

        System.out.println("All threads have completed their tasks. Main thread can continue.");
    }

    static class Worker implements Runnable {
        private CountDownLatch latch;

        public Worker(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                // 模拟子线程执行任务
                Thread.sleep((long) (Math.random() * 1000));
                System.out.println("Task completed by thread: " + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown(); // 子线程完成任务后调用countDown减少计数器
            }
        }
    }
}

输出结果:

Task completed by thread: Thread-2
Task completed by thread: Thread-0
Task completed by thread: Thread-1
All threads have completed their tasks. Main thread can continue.

 案例二


/**
 * 使用CountDownLatch完成多个游戏玩家进度条的加载
 * 直到所有玩家进度条加载完毕,游戏就可以启动了
 */
public class ProgressBarWithCountDownLatch {
    public static void main(String[] args) throws InterruptedException {
        int numThreads = 3;
        CountDownLatch latch = new CountDownLatch(numThreads);

        for (int i = 0; i < numThreads; i++) {
            Thread thread = new Thread(new Task(latch, "Thread-" + i));
            thread.start();
        }

        latch.await(); // 等待所有线程加载完毕

        System.out.println("All progress bars have completed. Main t
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值