This is the 27th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Utility class

CountDownLatch

This is done with a counter whose initial value is the number of threads. Each time a thread completes, the counter has a value of -1. When the counter has a value of 0, it indicates that all threads have completed, and the threads waiting on the lock can resume work.

CountDownLatch CountDownLatch = new CountDownLatch(5); CountDownLatch CountDownLatch = new CountDownLatch(5); for (int i = 0; i < 5; I++) {new Thread(()->{countdownlatch.countdown (); System.out.println(Thread.currentThread().getName()+":"+countDownLatch.getCount()); },String.valueOf(i)).start(); } // When the number becomes 0, await() is awakened and the following code continues, countdownlatch.await () is not executed if it does not become 0; System.out.println("111");Copy the code

Here we find that count does not change to 0, the loop ends, and we cannot output 111 without getting awaked to await it

CyclicBarrier

Add counter. When the increment reaches the specified number, the inside method is executed

CyclicBarrier cyclicBarrier = new cyclicBarrier (5,()->{cyclicBarrier = new cyclicBarrier (5,()->{ System.out.println(" When cyclicBarrier reaches 5, this statement will be printed "); }); for (int i = 0; i < 4; I++) {new Thread(()->{try {cyclicBarrier. Await (); System.out.println(Thread.currentThread().getName()+":"+cyclicBarrier.getNumberWaiting()); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } },String.valueOf(i)).start(); }Copy the code

Difference between CountDownLathc and CyclicBarrier

1.CountDownLathc is one-time and will stop when the conditions are met

CyclicBarrier is reusable

semaphore

It’s like a license. Only the person with the license can perform the operation. Release the license to someone else after the operation.

Public Semaphore(int permits) {sync = new NonfairSync(permits); // Permitting public Semaphore(int permits) {sync = new NonfairSync(permits); } / / get a lock public void acquire () throws InterruptedException {sync. AcquireSharedInterruptibly (1); }Copy the code
Semaphore Semaphore = new Semaphore(3); for (int i = 1; i <=6 ; I++) {new Thread(()->{try {// if semaphore.acquire(); if semaphore.acquire(); System.out.println(thread.currentThread ().getName()+" lock "); // Wait 2 SECONDS to release timeunit.seconds.sleep (2); } catch (InterruptedException e) { e.printStackTrace(); }finally {// release the lock so that the license +1 semaphore.release(); System.out.println(thread.currentThread ().getName()+" release lock "); } }, String.valueOf(i)).start(); }Copy the code

Concurrent traffic limiting limits the maximum number of concurrent traffic