多線程-CountDownLatch,CyclicBarrier,Semaphore

1.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();
           },String.valueOf(i)).start();
       }
        countDownLatch.await();
       System.out.println(Thread.currentThread().getName()+ " 班長開始鎖門了---");
    }
}

 

 


 

2.CyclicBarrier

public class CyclicBarrierDemo {

    private static final Integer NUMBER= 7;

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER,() -> {
            System.out.println("集齊7顆龍珠召喚神龍!");
        });

        for(int i =1; i<=7; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() +" 顆龍珠被收集到了");
                    cyclicBarrier.await();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
    }
}

 

 


 

3.Semaphore

public class SemaphoreDemo {
    private static final Integer Number = 3;

    public static void main(String[ ]args)  {

        Semaphore semaphore = new Semaphore(Number);
        //模擬6輛汽車搶3個停車位
        for(int i = 1; i<= 6; i++ ) {
            new Thread(() -> {
                try {

                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() +" 號車搶到停車位!");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println(Thread.currentThread().getName() +" -----號車離開了停車位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)).start();

        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章