多线程(十一): 计数器CountDownLatch和CyclicBarrier

本文介绍Java中线程的控制方式,包括使用join方法确保线程按顺序执行,利用CountDownLatch进行多线程间的同步,以及通过CyclicBarrier来协调一组线程的运行。

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

public static void main(String[] args) {
    System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t\trunning...");
    Thread thread = new Thread(() -> {
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\trunning...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\tover");
    });

    Thread thread2 = new Thread(() -> {
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\trunning...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\tover");
    });

    thread.start();
    thread2.start();

    IntStream.range(0, 10).forEach(i -> {
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t\t i=" + i);
    });
}

该示例主线程、Thread-0、Thread-1都是并行执行的
这里写图片描述


让main方法的最后的循环体放到最后执行

public static void main(String[] args) throws InterruptedException {
    System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t\trunning...");

    Thread threadA = new Thread(() -> {
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\trunning...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\tover");
    }, "Thread-A");

    Thread threadB = new Thread(() -> {
        try {
            // 先启动后join
            threadA.start();
            // A join B 就是先执行A再执行B
            threadA.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\trunning...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\tover");
    }, "Thread-B");


    threadB.start();
    // B join mian, B先执行,然后再执行mian,
    // 当执行B的时候,发现A join B了,就先执行AA执行完,执行B,而Bjoin mian,所以main最后执行
    threadB.join();

    IntStream.range(0, 10).forEach(i -> {
        try { Thread.sleep(1000); } catch (InterruptedException e) { }
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t\t i=" + i);
    });
}

这里写图片描述


public static void main(String[] args) throws InterruptedException {
    CountDownLatch countDownLatch = new CountDownLatch(2);

    System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t\trunning...");

    Runnable runnable = () -> {
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\trunning...");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
        }
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\tover");
        // 减一:在线程体内部调用
        countDownLatch.countDown();
    };

    // Thread-0 和 Thread-1并行执行
    new Thread(runnable).start();
    new Thread(runnable).start();

    // 但是只有countDownLatch中的count=0时才会继续往下执行,否则是阻塞的
    countDownLatch.await();

    IntStream.range(0, 10).forEach(i -> {
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t\t i=" + i);
    });
}

这里写图片描述

join()和CountDownLatch

  • join也可以让某个线程执行完之后再执行另一个线程,即让线程之间有先后顺序,一般是让某个子线程加入父线程,两个线程之间有父子关系,join会释放锁

  • CountDownLatch是一种计数器,多个线程之间没有父子关系是平级的,当计数器为0的时候才能往下执行

  • 具体使用哪个要看线程之间是否有父子关系

CyclicBarrier: 用于控制所有线程的前面部分代码都完成时才能执行所有线程后部分的代码

package java.util.concurrent;

public class CyclicBarrier {
    // 
    private final int parties;

    public CyclicBarrier(int parties);

    // 每执行一次等待方法,计数器就减1,计数器大于0之前等待方法就会阻塞暂停后面的代码的执行
    // 当计数器为0,所有线程的等待后面的代码并发执行

    public int await() throws InterruptedException, BrokenBarrierException;
}
public static void main(String[] args) throws InterruptedException {
    System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\t\trunning...");

    CyclicBarrier cyclicBarrier = new CyclicBarrier(5);

    Runnable runnable = () -> {
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\trunning...");
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
        }

        try { cyclicBarrier.await(); } catch (Exception e) { }
        System.out.println(new Date() + "\t" + Thread.currentThread().getName() + "\tover");
    };


    IntStream.range(0, 5).forEach(i -> {
        new Thread(runnable).start();
    });
}

这里写图片描述

CountDownLatch与CyclicBarrier比较

  • CountDownLatch: 计数器自己可以在任意地方减1 countDown(), await()方法在线程外调用,当计数器为0的时候才可以执行线程外的后面的代码
    • CyclicBarrier:在线程内调用await(),计数器会自动减1,用于控制线程内的后面的代码的执行
    • CountDownLatch用来控制线程外的代码,用于阻塞父线程的代码,CyclicBarrier用于控制线程内的代码,用于阻塞当前线程的代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

风流 少年

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

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

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

打赏作者

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

抵扣说明:

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

余额充值