计数器CyclicBarrier/CountDownLatch,Semaphore信号量

+1计数器CyclicBarrier

package add;

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

/**CyclicBarrier  +1计数器
 * @author liu
 */
public class CyclicBarrierA {
    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
            System.out.println("召唤神龙成功");
        });
        for (int i = 1; i <=7 ; i++) {
            final int finalI = i;
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"收集了"+ finalI +"个龙珠");
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

-1计数器CountDownLatch

package add;

import java.util.concurrent.CountDownLatch;

/**CountDownLatch  -1计数器
 * @author liu
 */
public class CountDownLatchA {
    public static void main(String[] args) throws InterruptedException {
        //总数是6,必须要执行的任务的时候再使用
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <=6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+" GO OUT");
                //计数减一
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
        //等待计数器归零,然后再向下执行
        countDownLatch.await();
        System.out.println("close  door");
    }
}

Semaphore信号量

package add;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreA {
    public static void main(String[] args) {
        //线程数量:停车位!限流,限制3个进入
        Semaphore semaphore = new Semaphore(3);
        for (int i = 1; i <=6; i++) {
            new Thread(()->{
                try {//acquire 得到
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到车位");
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(Thread.currentThread().getName()+"离开车位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    //release 释放
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }

    }
}
posted @ 2022-03-22 15:28  小幼虫虫  阅读(30)  评论(0)    收藏  举报