juc之CountDownLatch,CyclicBarrier,Semaphore的使用

 CountDownLatch是为了让某些必要的线程先执行完,然后再执行其它操作,作为一个计数使用,当它里面的值为0时,await下面才会走。

package com.example.demo;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchDemo {

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

        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i=0;i<6;i++){
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+":结束!!");
                countDownLatch.countDown();
            }).start();
        }

        countDownLatch.await();

        System.out.println(Thread.currentThread().getName()+":结束!!");
    }
}

CyclicBarrier和CountDownLatch是相反的,它是最开始是0,当调await方法相当于加1,等加到6的时候执行第二个参数里的线程。

package com.example.demo;

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

public class CyclicBarrierDemo {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(6,()->{
            System.out.println("最终执行!!");
        });

        for (int i=0;i<6;i++){
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"执行!");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

Semaphore就好比一个线程池一样,始终只能占用三个,但是线程池得关闭,否则一直执行,而Semaphore不需要。

package com.example.demo;

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

public class SemaphoreDemo {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);

        for (int i=0;i<6;i++){
            new Thread(()->{
                try {
                    semaphore.acquire(); //占用
                    System.out.println(Thread.currentThread().getName()+":执行开始");
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread().getName()+":执行结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release(); //释放
                }
            },i+"").start();
        }
    }
}

 

你可能感兴趣的:(juc)