Three auxiliary classes of JUC

Keywords: Java JUC

scene

Three commonly used auxiliary classes are provided in JUC. These auxiliary classes can well solve the frequent operation of Lock lock when there are too many threads. The three auxiliary classes are:
• CountDownLatch: decrease count
• CyclicBarrier: Circular barrier
• Semaphore: signal light

Decrease count CountDownLatch

CountDownLatch class can set a counter, and then use the countDown method to subtract 1. Use the await method to wait for the counter not greater than 0, and then continue to execute the statements after the await method.

• CountDownLatch mainly has two methods. When one or more threads call the await method, these threads will block
• other threads calling the countDown method will decrease the counter by 1 (the thread calling the countDown method will not block)
• when the value of the counter changes to 0, the thread blocked by the await method will wake up and continue to execute

Case: the waiter can't close the door until all the customers have finished eating

  public static void main(String[] args) throws InterruptedException {
        // Ten customers are eating
        CountDownLatch downLatch = new CountDownLatch(10);
        for (int i = 0; i < 10; i++) {
            int fa = i;
            new Thread(() -> {
                try {
                    System.out.println("----" + fa + "Table customer is finished,leave-----");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                downLatch.countDown();
            }).start();
        }
        downLatch.await();
        System.out.println("---The waiter began to clean the hotel---");
    }

Cyclic barrier

CyclicBarrier can be seen from the English words that it probably means circular blocking. In use, the first parameter of the CyclicBarrier construction method is the number of target obstacles. Each time the CyclicBarrier is executed, the number of obstacles will be increased by one. If the target number of obstacles is reached, the statements after cyclicBarrier.await() will be executed. CyclicBarrier can be understood as a plus one operation

CyclicBarrier contact CountDownLatch
The main connections and differences between CountDownLatch and CyclicBarrier are as follows:
1. Lock CountDownLatch to make a minus count, while the fence CyclicBarrier is an plus count.
2.CountDownLatch is one-time, and CyclicBarrier can be reused.
3.CountDownLatch emphasizes that one thread and multiple threads complete something. CyclicBarrier means that multiple threads wait for each other to complete.

Case: Qin destroyed the six Kingdoms

public static void main(String[] args) throws BrokenBarrierException, InterruptedException {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(6,()->{
            System.out.println("Unified China");
        });
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Destroyed");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, Country.CHU.getName()).start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Destroyed");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, Country.QI.getName()).start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Destroyed");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, Country.HAN.getName()).start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Destroyed");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, Country.WEI.getName()).start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Destroyed");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, Country.YAN.getName()).start();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "Destroyed");
            try {
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }, Country.ZHAO.getName()).start();

    }

Semaphore

The first parameter passed in the Semaphore construction method is the maximum Semaphore (which can be regarded as the maximum thread pool). Each Semaphore is initialized to one, and at most one license can be distributed. Use the acquire method to obtain the license, and the release method to release the license

Case: there are five parking spaces downstairs. 100 cars came

  public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        // 10 vehicles and 5 parking spaces (license)
        for (int i = 0; i < 100; i++) {
            int finalI = i;
            new Thread(()->{
                // Licensing
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName() + finalI +"The car is parked");
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    // release
                    System.out.println(Thread.currentThread().getName() +finalI + "The car withdrew");
                    semaphore.release();
                }
            },"x Brand car").start();
        }
    }

Posted by Akenatehm on Fri, 19 Nov 2021 23:13:35 -0800