Common auxiliary classes

Time:2021-9-18

CountDownLatch

Subtraction counter
Common auxiliary classes

import java.util.concurrent.CountDownLatch;

//Counter
public class CountDownLatchDemo {
    public static void main(String[] args) throws InterruptedException {
        //The total number is 6. It can be used when the task must be performed
        CountDownLatch countDownLatch = new CountDownLatch(6);

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                System.out.println(Thread.currentThread().getName()+" Go out");
                countDownLatch.countDown();
            },String.valueOf(i)).start();
        }

        countDownLatch.await();// Wait for the counter to return to zero and execute down

        System.out.println("close door");
    }

}

Principle:
countDownLatch.countDown();Quantity – 1
countDownLatch.await();Wait for the counter to return to zero and execute down
Each time a thread calls countdown(), the number is – 1. Assuming that the counter becomes 0, countdownlatch. Await(); Wake up, continue!

CyclicBarrier

Addition counter: specify the number of threads and perform the following operations after execution
Common auxiliary classes

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

public class CyclicBarrierDemo {
    public static void main(String[] args) {
        /**
         *Gather 7 dragon balls and summon the Dragon
         */

        //Thread calling Dragon Ball
        //If it is 8, only 7 threads will remain stuck
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
            System. Out. Println ("summon dragon successfully!");
        });

        for (int i = 1; i <= 7; i++) {
            final int temp = i;
            //Can lambda operate on variable I
            new Thread(()->{
                System. Out. Println (thread. Currentthread(). Getname() + "collect" + temp + "dragon beads");
                try {
                    cyclicBarrier.await();// wait for
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();

        }
    }
}

Semaphore

Semaphore: there can only be a specified number of threads at a time
Common auxiliary classes

Grab a parking space!
6 vehicles – 3 parking spaces

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

public class SemaphoreDemo {
    public static void main(String[] args) {
        //Number of threads: available when current is limited
        Semaphore semaphore = new Semaphore(3);

        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                //Acquire() gets
                try {
                    semaphore.acquire();
                    System. Out. Println (thread. Currentthread(). Getname() + "grab parking space");
                    TimeUnit.SECONDS.sleep(2);
                    System. Out. Println (thread. Currentthread(). Getname() + "leaving parking space");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    //Release
                    semaphore.release();
                }

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

Principle:
semaphore.acquire();Get, assume it’s full, wait, wait until it’s released
semaphore.release();Release, the current semaphore will be released + 1, and then wake up the waiting thread!
Function: multiple shared resources are mutually exclusive, concurrent flow restriction, and control the maximum number of threads!

This work adoptsCC agreement, reprint must indicate the author and the link to this article

Recommended Today

Seven Python code review tools recommended

althoughPythonLanguage is one of the most flexible development languages at present, but developers often abuse its flexibility and even violate relevant standards. So PythoncodeThe following common quality problems often occur: Some unused modules have been imported Function is missing arguments in various calls The appropriate format indentation is missing Missing appropriate spaces before and after […]