Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
1, CountDownLatch
CountDownLatch profile
CountDownLatch is a synchronization utility class under JUC that allows one thread to wait for other threads to complete their work before continuing. This is implemented using a counter. The initial value of the counter is the number of threads. As each thread completes its task, the counter is reduced by one. When the counter value is 0, all threads have completed some task, and the threads waiting on CountDownLatch can resume to perform the next task.
A CountDownLatch for a CountDownLatch acts as a simple open/close latch, or door: all threads call await ‘and wait at the door until the thread called countDown() opens. A CountDownLatch initialization N can be used to do a thread wait until N threads have completed an operation or some action has been completed N times.
CountDownLatch is a common method
CountDownLatch(int count)
Initialize CountDownLatch for the specified value.
Parameter: count indicates the count value
2, countDown ()
Reduces the count of the latch, and releases all waiting threads if the count reaches zero.
If the current count is greater than 0, it is decremented, and if the new count is 0, all waiting threads are re-enabled for thread scheduling.
3, await ()
Make the current thread wait for a latch count of 0 unless the thread is interrupted.
If the current count is 0, this method returns immediately.
If the current count is greater than zero, the current thread is disabled for thread scheduling and dormant until one of two things happens:
- The count reaches zero due to the call to the countDown() method
- Some other threads interrupts the current thread
4, await(long timeout,TimeUnit unit)
Causes the current thread to wait until the latch countdown reaches zero, unless the thread is interrupted or the specified wait time has expired.
If the current count is zero, this method immediately returns true.
If the current count is greater than zero, the current thread is disabled for thread scheduling purposes and sleeps until one of three things happens:
Because the countDown method is called, the count reaches zero;
Or some other thread interrupts the current thread;
Or the specified wait time has expired.
This method returns true if the count reaches zero.
If the current thread: sets the disconnection state when entering this method; Or it can be interrupted while waiting, then throw InterruptedException and clear the interrupted status of the current thread.
Returns false if the specified wait time has elapsed. If the time is less than or equal to zero, the method does not wait at all.
Parameters:
Timeout Indicates the maximum waiting time
Unit – timeout Indicates the time unit of the parameter
Returns: true if the count reaches zero or false if a wait time has elapsed before the count reaches zero
Throws: InterruptedException – if the current thread is interrupted while waiting
CountDownLatch use case
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
// Initialize a latch with a value of 5
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"Go out");
countDownLatch.countDown();// The value of the latch is
},String.valueOf(i)).start();
}
countDownLatch.await();// Let the current thread wait until the latch count reaches zero, then proceed
System.out.println("Wait for thread to start being called"); }}Copy the code
2, CyclicBarrier
CyclicBarrier profile
CyclicBarrier is a synchronization helper class that allows a set of threads to all wait for each other to reach a common barrier point. CyclicBarriers are useful in programs that involve groups of threads of fixed size that must occasionally wait on each other. The barrier is circular because it can be reused after waiting for the thread to be released.
CyclicBarrier supports the optional Runnable command, which runs once at each barrier point, after the last thread in a set of threads arrives, but before any threads are released. This barrier operation is useful for updating the state of the share before either party continues.
The CyclicBarrier class allows a group of threads to wait for each other until all threads have reached a barrier point.
CyclicBarrier common methods
1. Construction method:
CyclicBarrier(int parties, Runnable barrierAction) : Creates a new CyclicBarrier that will be triggered when a given number of parties (threads) wait,
And performs the given barrier action when the barrier is triggered, by the last thread to enter the barrier.
Argument: parties The number of threads that must call await before the barrier is triggered
BarrierAction Command executed when an obstacle is triggered, or null if no action is taken
CyclicBarrier(int parties) : Creates a new CyclicBarrier that will trip when a given number of participants (threads) are waiting for it, and when the barrier trips
Does not perform predefined operations.
2, await ()
Wait until all threads have called await, and the thread calls await() to indicate that it has reached the barrier,
If the current thread is not the last thread to arrive, it is disabled for thread scheduling purposes and sleeps until one of the following occurs:
-
The last thread arrives;
-
Or some other thread interrupts the current thread;
-
Or some other thread interrupts one of the other waiting threads;
-
Or some other thread timed out while waiting for the barrier;
-
Or some other thread calls reset() on the barrier (to reset the barrier to its initial state).
Returns: the arrival index of the current thread, where index getParties(), -1 for the first arrival and zero for the last
3, await(long timeout, TimeUnit unit)
Wait for all participants to call await on this barrier, or the specified wait time has expired.
If the current thread is not the last thread to arrive, it is disabled for thread scheduling purposes and sleeps until one of the following occurs:
-
The last thread arrives;
-
Or the specified timeout period has expired;
-
Or some other thread interrupts the current thread;
-
Or some other thread interrupts one of the other waiting threads;
-
Or some other thread timed out while waiting for the barrier;
-
Or some other thread calls reset() on the barrier (to reset the barrier to its initial state).
CyclicBarrier use cases
public class CyclicBarrierDemo {
public static void main(String[] args) {
/ / create the CyclicBarrier
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> {
System.out.println("Gather seven dragon balls and summon the dragon!");
});
for (int i = 0; i < 7; i++) {
final int temp = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"Collected"+temp+"Dragon Ball");
try {
cyclicBarrier.await();The thread calls the await method
} catch (InterruptedException e) {
e.printStackTrace();
} catch(BrokenBarrierException e) { e.printStackTrace(); } }).start(); }}}Copy the code
3, Semaphore
Introduction of Semaphore
Semaphore, often called a Semaphore, can be used to control the number of threads accessing a particular resource at the same time, coordinating threads to ensure proper use of the resource.
Semaphores are usually used to limit the number of threads (stream limiting) rather than to access some (physical or logical) resource.
Semaphore common methods
1. Construction method
Semaphore(int permits) : Creates a Semaphore with a given number of permits and unfair permits.
Semaphore(int permits, Boolean fair) : Creates a Semaphore with a given number of permits and a given fair setting.
2, acquire ()
The current thread takes a license from this semaphore and blocks until a license is provided, otherwise the thread is interrupted.
Obtain a license (if any) and return it immediately, reducing the number of licenses available by one.
If no permissions are available, the current thread will be disabled for thread scheduling purposes and put to sleep until one of two things happens:
-
Some other thread calls the semaphore’s release method, and the current thread is next assigned a license;
-
Or some other thread interrupts the current thread.
3, the release ()
Release licenses, increasing the number of licenses available by one. If any thread attempts to obtain permission, select a thread and grant the permission just released.
Semaphore use case
This is a class that uses semaphores to control access to a resource:
public class SemaphoreDemo {
public static void main(String[] args) {
// Create a semaphore with 5 permissions and unfair fair Settings
Semaphore semaphore = new Semaphore(5);
for (int i = 0; i < 10; i++) {
new Thread(()->{
try {
semaphore.acquire();// Get the license
System.out.println(Thread.currentThread().getName()+"Thread starts executing");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+"Thread execution terminated");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release(); // Release the license} },String.valueOf(i)).start(); }}}Copy the code