Java 多线程中CountDownLatch对象的用途

 我们会遇到在主线程中开启多线程并行执行任务,且主线程要等待所有子线程执行完毕后再进行汇总的场景,
 CountDownLatch的内部提供了一个计数器,在初始化对象时设定它的初始值。
 另外它还提供了一个countDown方法来操作计数器的值,每调用一次countDown方法计数器都会减1,
 直到计数器的值减为0时就代表条件已成熟,所有因调用await方法而被阻塞的线程都会被唤醒。

范例1:线程1和线程2为并发线程,线程3和线程4在线程1和线程2执行完毕后再并发执行

package com.contoso;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample1 {

    private final CountDownLatch latch = new CountDownLatch(2);
    private int sum1 = 0, sum2 = 0, total = 0, sub1 = 0;
    private Thread t4 = null, t3 = null, t2 = null, t1 = null;

    private int sum(int a, int b) {
        return a + b;
    }

    private int sub(int a, int b) {
        return a - b;
    }

    public void calculate(int start, int mid, int end) {
        // 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 +  ...  + 100 = 5050
        t1 = new Thread(() -> {
            try {
                for (int i = start; i <= mid; i++) {
                    sum1 += i;
                }
                System.out.println(Thread.currentThread().getName() + " Calculate Sum1 = " + sum1);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }, "线程1");

        // 101 + 102 + 103 + 104 + 105 + 106 + 107 + 108 + 109 + 110 + 111 + 112 +  ... + 200 = 15050
        t2 = new Thread(() -> {
            try {
                for (int i = mid + 1; i <= end; i++) {
                    sum2 += i;
                }
                System.out.println(Thread.currentThread().getName() + " Calculate Sum2 = " + sum2);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }, "线程2");

        // 5050 + 15050 = 20100
        t3 = new Thread(() -> {
            try {
                latch.await();
                total = sum(sum1, sum2);
                System.out.println(Thread.currentThread().getName() + " Calculate Total = " + total);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程3");

        // 15050 - 5050 = 10000
        t4 = new Thread(() -> {
            try {
                latch.await();
                sub1 = sub(sum2, sum1);
                System.out.println(Thread.currentThread().getName() + " Calculate Sub1 = " + sub1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "线程4");

        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

    public static void main(String[] args) {
        CountDownLatchExample1 Example = new CountDownLatchExample1();
        Example.calculate(1, 100, 200);
    }
}
run:
线程1 Calculate Sum1 = 5050
线程2 Calculate Sum2 = 15050
线程4 Calculate Sub1 = 10000
线程3 Calculate Total = 20100
BUILD SUCCESSFUL (total time: 0 seconds)

范例2:线程1和线程2为并发线程,线程3和线程4在线程1和线程2执行完毕后再并发执行

package com.contoso;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchExample2 {

    ExecutorService executor = Executors.newCachedThreadPool();
    CountDownLatch latch = new CountDownLatch(2);
    private int sum1 = 0, sum2 = 0, total = 0, sub1 = 0;
    private int start = 0, mid = 0, end = 0;

    private int sum(int a, int b) {
        return a + b;
    }

    private int sub(int a, int b) {
        return a - b;
    }

    Runnable t1 = () -> {
        try {
            for (int i = start; i <= mid; i++) {
                sum1 += i;
            }
            System.out.println(Thread.currentThread().getName() + " Calculate Sum1 = " + sum1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    };
    Runnable t2 = () -> {
        try {
            for (int i = mid + 1; i <= end; i++) {
                sum2 += i;
            }
            System.out.println(Thread.currentThread().getName() + " Calculate Sum2 = " + sum2);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            latch.countDown();
        }
    };
    Runnable t3 = () -> {
        try {
            latch.await();
            total = sum(sum1, sum2);
            System.out.println(Thread.currentThread().getName() + " Calculate Total = " + total);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };
    Runnable t4 = () -> {
        try {
            latch.await();
            sub1 = sub(sum2, sum1);
            System.out.println(Thread.currentThread().getName() + " Calculate Sub1 = " + sub1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    };

    public void calculate(int start, int mid, int end) {
        this.start = start;
        this.mid = mid;
        this.end = end;
        executor.execute(t1);
        executor.execute(t2);
        executor.execute(t3);
        executor.execute(t4);
        executor.shutdown();
    }

    public static void main(String[] args) {
        CountDownLatchExample2 Example = new CountDownLatchExample2();
        Example.calculate(1, 100, 200);
    }

}
run:
pool-1-thread-1 Calculate Sum1 = 5050
pool-1-thread-2 Calculate Sum2 = 15050
pool-1-thread-3 Calculate Total = 20100
pool-1-thread-4 Calculate Sub1 = 10000
BUILD SUCCESSFUL (total time: 0 seconds)

范例3  3个线程代表斗地主的3个玩家,一旦3个玩家入座游戏便立即开始

package com.contoso;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class CountDownLatchExample3 {

    private static AtomicInteger players = new AtomicInteger(1);
    private static CountDownLatch latch = new CountDownLatch(3);

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" 【玩家" + players.getAndIncrement() + "】已入场 ");
                latch.countDown();
            }
        },"线程1:");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" 【玩家" + players.getAndIncrement() + "】已入场 ");
                latch.countDown();
            }
        },"线程2:");

        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+" 【玩家" + players.getAndIncrement() + "】已入场 ");
                latch.countDown();
            }
        },"线程3:");        
        // 启动所有的子线
        t1.start();
        t2.start();
        t3.start();
        Thread.currentThread().setName("主线程:");
        System.out.println(Thread.currentThread().getName()+"等待斗地主玩家入场");
        latch.await(); // 阻塞主线程一直等待所有的子线程执行完毕,然后唤醒主线程继续向后执行
        System.out.println(Thread.currentThread().getName()+"三位玩家已入座,开始发牌 ... ...");
    }
}
run:
主线程:等待斗地主玩家入场
线程3: 【玩家1】已入场 
线程2: 【玩家2】已入场 
线程1: 【玩家3】已入场 
主线程:三位玩家已入座,开始发牌 ... ...
BUILD SUCCESSFUL (total time: 3 seconds)

范例4:火箭发射前的多线程检查任务

package com.myth;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CountDownLatchDemo implements Runnable {

    static final CountDownLatch latch = new CountDownLatch(10);
    static final CountDownLatchDemo demo = new CountDownLatchDemo();

    @Override
    public void run() {
        try {
            // 模拟检查任务所需要的时间
            Thread.sleep(new Random().nextInt(10) * 1000);
            System.out.println(Thread.currentThread().getName() + "  模拟任务检查结束");
            latch.countDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService exec = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 10; i++) {
            exec.submit(demo);
        }
        // 等待检查
        latch.await();
        // 发射火箭
        System.out.println("点火!");
        exec.shutdown();
    }

}
run:
pool-1-thread-6  模拟任务检查结束
pool-1-thread-2  模拟任务检查结束
pool-1-thread-5  模拟任务检查结束
pool-1-thread-8  模拟任务检查结束
pool-1-thread-9  模拟任务检查结束
pool-1-thread-1  模拟任务检查结束
pool-1-thread-10  模拟任务检查结束
pool-1-thread-7  模拟任务检查结束
pool-1-thread-4  模拟任务检查结束
pool-1-thread-3  模拟任务检查结束
点火!
BUILD SUCCESSFUL (total time: 9 seconds)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值