java中CountDownLatch、CyclicBarrier和Semaphore

本文深入解析了Java中三种重要的并发控制工具:CountDownLatch用于线程等待所有其他线程执行完毕;CyclicBarrier使所有线程等待处于同一状态后继续执行;Semaphore作为信号量,控制线程访问共享资源。

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

CountDownLatch的作用,某一个线程等待所有其他的线程执行完毕或者执行到某一步。

使用示例:

public class VolatileTest {

    private volatile int i = 0;

    private void increate(){
        i++;
    }

    public static void main(String[] args){
        //创建CountDownLatch对象
        CountDownLatch countDownLatch = new CountDownLatch(10);
        VolatileTest t = new VolatileTest();
        for(int k=0;k<10;k++){
            new Thread(){
                public void run(){
                    for(int n=0;n<1000;n++) {
                        t.increate();
                    }
                    System.out.println("over!");
                    //执行完毕,调用此方法
                    countDownLatch.countDown();
                }
            }.start();
        }
        try {
            //等待10个线程执行完毕
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(t.i);
    }
}

CyclicBarrier的作用与CountDownLatch相反:是所有线程都等待大家都处在某一个状态(某一步),然后才能往下执行。

该对象可重复使用,可设置等待超时时间。

使用示例:

public class CyclicBarrierTest   implements Runnable{

    CyclicBarrier cb = null;
    String threadName = null;

    public CyclicBarrierTest(CyclicBarrier cb,String name){
        this.cb = cb;
        this.threadName = name;
    }

    @Override
    public void run() {
        try {
            Thread.sleep((int)Math.floor(Math.random()*2000)); //设置一个随机等待的时间,让效果明显
            System.out.println(String.format("%s is working now! ",threadName));
            //等待所有的线程
            cb.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
        System.out.println(String.format("All is Ok! ,%s is working again!",threadName));

    }

    public static void main(String[] args){
        //构造方法
        CyclicBarrier cb =new CyclicBarrier(3);
        for (int i=0;i<3;i++){
            CyclicBarrierTest t = new CyclicBarrierTest(cb,"thread-"+i);
            new Thread(t).start();
        }
    }
}

Semaphore,信号量,类似于锁,只有线程获取到了许可,才可以执行。

方法:acquire()获取许可,没有获取到则等待;

release()释放许可;

boolean tryAcquire()尝试获得许可,没有获取到则立即返回false,获取到则返回true;

示例:

public class SemaphoreTest extends Thread {
    Semaphore semaphore = null;
    String name = null;

    public SemaphoreTest(Semaphore semph, String name) {
        this.semaphore = semph;
        this.name = name;
    }

    public void run() {
        try {
            semaphore.acquire();
            System.out.println(String.format(" %s get a semaphore, now I am doing work!", name));
            Thread.sleep(3000);
            System.out.println(String.format(" %s have finished work!", name));
            semaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        Semaphore semaphore = new Semaphore(3);
        for(int i=0;i<10;i++){
            SemaphoreTest t = new SemaphoreTest(semaphore,"thread-"+i);
            t.start();
        }
    }
}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值