JUCでよく使われる3つの補助クラス

11284 ワード

CountDownLatch
テスト:
public class CountDownLatchDemo {

    //  
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(6);
        for (int i = 1; i <=10; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName());
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }
//        countDownLatch.await();
        System.out.println("  -> ");

    }
}


印刷:
  -> 
1
10
9
7
6
8
2
4
3
5


CountDownLatchはカウンタと見なすことができ、コアメソッドは以下の通りである.
1、countDownLatch.countDown(); カウント初期値マイナス1
2、countDownLatch.await(); カウンタが0になるとcountDownLatch.await()が起動し、プログラムを実行し続けます!
cyclicBarrier
//  
public class CyclicBarrierDemo {

    public static void main(String[] args) {

        CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
            System.out.println(" ");
        });

        for (int i = 1; i <= 7; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    System.out.println("  " + String.valueOf(finalI) + " ");
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }, Thread.currentThread().getName()).start();
        }
    }

}


cyclicBarrier.await()メソッドはCyclicBarrierを待機させ、スレッド数がしきい値に達するとトリガーされます.次はCyclicBarrierのコンストラクション関数です.2番目のパラメータはRunableインタフェースで、lambda式で書くことができます.
public CyclicBarrier(int parties, Runnable barrierAction) {
    this.lock = new ReentrantLock();
    this.trip = this.lock.newCondition();
    this.generation = new CyclicBarrier.Generation();
    if (parties <= 0) {
        throw new IllegalArgumentException();
    } else {
        this.parties = parties;
        this.count = parties;
        this.barrierCommand = barrierAction;
    }
}

Semaphore
public class SemaphoreDemo {
    //  
    public static void main(String[] args) {

        //  3   
        Semaphore semaphore = new Semaphore(3);

        /**
         * 1、         semaphore.acquire();  ,  ,  ,  
         * 2、         semaphore.release();  ,  + 1, !
         *  :  ! , 
         */
        for (int i = 1; i <= 6; i++) {
            new Thread(() -> {
                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();
                    //  
                }
            }, String.valueOf(i)).start();
        }
    }
}