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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/vbirdbest/article/details/81808282
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用于控制线程内的代码,用于阻塞当前线程的代码

猜你喜欢

转载自blog.csdn.net/vbirdbest/article/details/81808282