1. 程式人生 > 實用技巧 >JUC三大常用輔助類

JUC三大常用輔助類

JUC三大常用輔助類

CountDownLatch

// 計數器
public class CountDownLatchDemo {
    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(); // 數量-1
            },String.valueOf(i)).start();
        }

        countDownLatch.await(); // 等待計數器歸零,然後再向下執行

        System.out.println("Close Door");

    }
}

原理:

countDownLatch.countDown(); // 數量-1

countDownLatch.await(); // 等待計數器歸零,然後再向下執行 每次有執行緒呼叫 countDown() 數量-1,假設計數器變為0,countDownLatch.await() 就會被喚醒,繼續 執行!

CyclicBarrier

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        /**
         * 集齊7顆龍珠召喚神龍
         */
        // 召喚龍珠的執行緒
        CyclicBarrier cyclicBarrier = new CyclicBarrier(8,()->{
            System.out.println("召喚神龍成功!");
        });

        for (int i = 1; i <=7 ; i++) {
            final int temp = i;
            // lambda能操作到 i 嗎
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"收集"+temp+"個龍珠");
                try {
                    cyclicBarrier.await(); // 等待
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }
}

Semaphore

與作業系統中的訊號量一樣

搶車位!
6車---3個停車位置

public class SemaphoreDemo {
    public static void main(String[] args) {
        // 執行緒數量:停車位! 限流!
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <=6 ; i++) {
            new Thread(()->{
                // acquire() 得到
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"搶到車位");
                    TimeUnit.SECONDS.sleep(2);
                    System.out.println(Thread.currentThread().getName()+"離開車位");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    semaphore.release(); // release() 釋放
                }

            },String.valueOf(i)).start();
        }

    }
}

原理:

semaphore.acquire() 獲得,假設如果已經滿了,等待,等待被釋放為止!

semaphore.release() 釋放,會將當前的訊號量釋放 + 1,然後喚醒等待的執行緒! 作用: 多個共享資源互斥的使用!併發限流,控制最大的執行緒數!

視訊參考https://www.bilibili.com/video/BV1B7411L7tE
上一篇:Callable介面
下一篇:讀寫鎖