Java 中的 CountDownLatch, CyclicBarrier, Semaphore

1、CountDownLatch

CountDownLatch 主要用于一个线程需要等到其他线程完成任务后继续执行的场景。CountDownLatch 不可重用。

示例:

package site.iway;

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

public class Main {

    private static final int WORKER_COUNT = 3;

    private static CountDownLatch sCountDownLatch = new CountDownLatch(WORKER_COUNT);

    private static class WorkThread extends Thread {

        public void run() {
            System.out.println(Thread.currentThread().getName() + " start working...");
            try {
                Random random = new Random(System.nanoTime());
                int workTime = random.nextInt(3000);
                Thread.sleep(workTime);
            } catch (InterruptedException e) {
                // nothing
            }
            System.out.println(Thread.currentThread().getName() + " finish working.");
            sCountDownLatch.countDown();
        }

    }

    public static void main(String[] args) {
        System.out.println("MainThread start creating workers...");
        for (int i = 0; i < WORKER_COUNT; i++) {
            WorkThread workThread = new WorkThread();
            workThread.setName("WorkThread-" + i);
            workThread.start();
        }
        System.out.println("MainThread finished creating workers, and begin wait for workers to finish their jobs...");
        try {
            sCountDownLatch.await();
        } catch (InterruptedException e) {
            // nothing
        }
        System.out.println("All workers finished their jobs, MainThread continue. ");
    }

}

这里有个问题,假设在 sCountDownLatch.await(); 之前,就已经有部分 WorkThread 完成了它们的工作,代码将如何运行?通过在 sCountDownLatch.await();  之前加入等待时间并经过多次实验,发现并未影响输出结果,针对这个具体原理可以查看 CountDownLatch 的源码。

输出:

MainThread start creating workers...
MainThread finished creating workers, and begin wait for workers to finish their jobs...
WorkThread-0 start working...
WorkThread-1 start working...
WorkThread-2 start working...
WorkThread-0 finish working.
WorkThread-2 finish working.
WorkThread-1 finish working.
All workers finished their jobs, MainThread continue. 

2、CyclicBarrier

CyclicBarrier,译为回环栅栏,主要用于多个线程等待至某一状态后同时继续执行的场景。CyclicBarrier 是可以重用的。

示例:

package site.iway;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class Main {

    private static final int WORKER_COUNT = 3;

    private static CyclicBarrier sCyclicBarrier = new CyclicBarrier(WORKER_COUNT);

    private static class WorkThread extends Thread {

        public void run() {
            System.out.println(Thread.currentThread().getName() + " start working...");
            try {
                Random random = new Random(System.nanoTime());
                int workTime = random.nextInt(3000);
                Thread.sleep(workTime);
            } catch (InterruptedException e) {
                // nothing
            }
            System.out.println(Thread.currentThread().getName() + " finish working and start wait for other workers");
            try {
                sCyclicBarrier.await();
            } catch (InterruptedException e) {
                // nothing
            } catch (BrokenBarrierException e) {
                // nothing
            }
            System.out.println(Thread.currentThread().getName() + " continue.");
        }

    }

    public static void main(String[] args) {
        for (int i = 0; i < WORKER_COUNT; i++) {
            WorkThread workThread = new WorkThread();
            workThread.setName("WorkThread-" + i);
            workThread.start();
        }
    }

}

输出:

WorkThread-0 start working...
WorkThread-1 start working...
WorkThread-2 start working...
WorkThread-0 finish working and start wait for other workers
WorkThread-2 finish working and start wait for other workers
WorkThread-1 finish working and start wait for other workers
WorkThread-0 continue.
WorkThread-1 continue.
WorkThread-2 continue.

3、Semaphore

Semaphore,译为信号量,主要用于多线程竞争有限的资源的场景。

示例:

package site.iway;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class Main {

    private static final int WORKER_COUNT = 5;

    private static final int NEEDED_RESOURCE_COUNT = 2;

    private static Semaphore sSemaphore = new Semaphore(WORKER_COUNT);

    private static class WorkThread extends Thread {

        public void run() {
            System.out.println(Thread.currentThread().getName() + " start waiting for resources.");
            try {
                sSemaphore.acquire(NEEDED_RESOURCE_COUNT);
            } catch (InterruptedException e) {
                // nothing
            }
            System.out.println(Thread.currentThread().getName() + " got resources and start working.");
            try {
                Random random = new Random(System.nanoTime());
                int workTime = random.nextInt(3000);
                Thread.sleep(workTime);
            } catch (InterruptedException e) {
                // nothing
            }
            System.out.println(Thread.currentThread().getName() + " finished working and release resources.");
            sSemaphore.release(NEEDED_RESOURCE_COUNT);
        }

    }

    public static void main(String[] args) {
        for (int i = 0; i < WORKER_COUNT; i++) {
            WorkThread workThread = new WorkThread();
            workThread.setName("WorkThread-" + i);
            workThread.start();
        }
    }

}

输出:

WorkThread-0 start waiting for resources.
WorkThread-2 start waiting for resources.
WorkThread-4 start waiting for resources.
WorkThread-3 start waiting for resources.
WorkThread-0 got resources and start working.
WorkThread-1 start waiting for resources.
WorkThread-2 got resources and start working.
WorkThread-0 finished working and release resources.
WorkThread-4 got resources and start working.
WorkThread-2 finished working and release resources.
WorkThread-3 got resources and start working.
WorkThread-4 finished working and release resources.
WorkThread-1 got resources and start working.
WorkThread-3 finished working and release resources.
WorkThread-1 finished working and release resources.

注意,在资源使用完毕之后,务必释放资源,否则其他等待的线程会出现饿死现象。

Semaphore 构造器中有个 boolean 类型的参数 fair 代表是否为公平锁,公平和非公平锁的区别很简单,判断依据为是否依照等待顺序,公平的会按照等待顺序一个一个来,而非公平则不一定按照等待顺序。在类的内部实现中为一个队列。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值