Java并发工具类-CountdownLatch,CyclicBarrier和Semaphore

CountDownLatch

CountDownLatch从字面意思上来看,它是一个向下计数锁,可以用来进行线程间的调度,主要方法如下:

    public CountDownLatch(int count) {
        if (count < 0) throw new IllegalArgumentException("count < 0");
        this.sync = new Sync(count);
    }

    public void await() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    public boolean await(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

    public void countDown() {
        sync.releaseShared(1);
    }

    public long getCount() {
        return sync.getCount();
    }

构造函数只有一个,接受一个整数证,作为该对象的初始数值。方法也很简单:

  • await() 进入阻塞状态,直到count为0为止
  • boolean await(long timeout, TimeUnit unit) 同上,但是可以指定超时时间,超时返回false
  • void countDown() 计数减1
  • public long getCount() 获取当前计数

使用方法也非常简单:

 final CountDownLatch latch = new CountDownLatch(3);

        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i =0; i<5; i++){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    latch.countDown();
                    System.out.println("current count: " + latch.getCount());
                }
            }
        }).start();

        new Thread(new Runnable(){

            @Override
            public void run() {
                try {
                    latch.await();
                    System.out.println("latch released.....");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }).start();

    //执行结果:
    current count: 2
    current count: 1
    latch released.....
    current count: 0
    current count: 0
    current count: 0

CyclicBarrier

CyclicBarrier意思是回环栅栏,它的作用是为当前线程设置一个栅栏,挂起当前线程,直到挂起的线程数达到指定数量时才一起放行。Cyclic的意思是说,在放行以后,栅栏是可以被重复使用的。

主要方法如下:


    public CyclicBarrier(int parties, Runnable barrierAction) {
        if (parties <= 0) throw new IllegalArgumentException();
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }

    public CyclicBarrier(int parties) {
        this(parties, null);
    }

    public int await() throws InterruptedException, BrokenBarrierException {
    }

    public int await(long timeout, TimeUnit unit)
        throws InterruptedException,
               BrokenBarrierException,
               TimeoutException {
        return dowait(true, unit.toNanos(timeout));
    }

    public int getNumberWaiting() {
    }

    public int getParties() {
        return parties;
    }

  • CyclicBarrier(int parties, Runnable barrierAction) 整数parties指定该barrier需要挂起的线程数,barrierAction表示barrier放行以后执行的动作,选定任意一个线程执行
  • int await() 进入挂起状态,返回值为剩余的线程数。可以被打断或者调用reset方法抛出异常来终止挂起状态,但是reset方法不建议使用,会导致不同线程间调度变得极为复杂。
  • int await(long timeout, TimeUnit unit)同上
  • int getNumberWaiting()获取当前挂起的线程数
  • int getParties()获取指定的线程数

下边是简单的例子:

    final CyclicBarrier barrier = new CyclicBarrier(3, new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + " execute barrier runnable.");
            }
        });

    for(int i = 0; i < 5; i++){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {

                        System.out.println(Thread.currentThread().getName() + " index: " +  barrier.await());

                    } catch (BrokenBarrierException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    System.out.println(Thread.currentThread().getName() + " start...");
                }
            },("T"+ i)).start();
        }
    }

    执行结果如下:
    T2 execute barrier runnable. //放行以后执行barrier指定的任务
    T2 index: 0//T2 是最后开启的线程,返回值为0表示barrier达到放行条件
    T2 start...
    T0 index: 2//T0 是第一个开启的线程,返回值为2表示barrier还需要挂起两个线程才能放行
    T0 start...
    T1 index: 1//T1 是第二个开启的线程,返回值为1表示barrier还需要挂起1个线程才能放行
    T1 start...
    //此时还有两个线程处于挂起状态

Semaphore

Semaphore是信号量的意思,它更像是一种可以指定持有数量的锁,该锁的持有对象满足数量之后,其他要获取锁的对象只能等待其他对象释放。

它的主要方法如下:

    public Semaphore(int permits) {
        sync = new NonfairSync(permits);
    }
    public Semaphore(int permits, boolean fair) {
        sync = fair ? new FairSync(permits) : new NonfairSync(permits);
    }
    public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

    public void acquire(int permits) throws InterruptedException {
        if (permits < 0) throw new IllegalArgumentException();
        sync.acquireSharedInterruptibly(permits);
    }

    public void acquireUninterruptibly() {
        sync.acquireShared(1);
    }

    public void release() {
        sync.releaseShared(1);
    }

    public void release(int permits) {
        if (permits < 0) throw new IllegalArgumentException();
        sync.releaseShared(permits);
    }

    public boolean tryAcquire() {
        return sync.nonfairTryAcquireShared(1) >= 0;
    }
  • Semaphore(int permits)指定持有者数量
  • Semaphore(int permits, boolean fair) 可以指定是否实现为公平锁
  • acquire()获取1个信号量
  • acquire(int permits) 获取指定的信号量数量
  • acquireUninterruptibly()等待状态不能被打断
  • release()释放信号量
  • release(int permits)释放指定数量的信号量
  • boolean tryAcquire()尝试获取信号量,不阻塞,直接返回,false表示获取失败

你可能感兴趣的:(Java并发工具类-CountdownLatch,CyclicBarrier和Semaphore)