Java concurrent programming summary 12: Concurrency tools: Semaphore, Exchanger, CountDownLatch, CyclicBarrier

Refer to the blog previously written:
Detailed Java concurrency tools: Semaphore, Exchanger

And: Java concurrency tools in the vernacular-CountDownLatch, CyclicBarrier

 

 

General summary:

1. Semaphore can be understood as a semaphore , used to control the number of threads that resources can be accessed concurrently, to ensure that multiple threads can reasonably use specific resources.

Semaphore is equivalent to a license. The thread needs to obtain the license through the acquire method before the thread can continue to execute, otherwise it can only block and wait in this method. When the business function is executed, release()the license needs to be returned by a method so that other threads can obtain the license to continue execution.

Semaphore is particularly suitable in application scenarios where resource usage is restricted.

acquire、tryAcquire、release;

 

2. Exchanger is a tool class used for collaboration between threads, used to exchange between two threads. It provides a synchronization point for exchange , at which two threads can exchange data.

The specific exchange of data is achieved through the exchange method. If one thread executes the exchange method first, it will wait for the other thread to execute the exchange method simultaneously. At this time, both threads have reached the synchronization point, and the two threads can exchange data.

3、CountDownLatch

When multiple threads cooperate to complete business functions, sometimes it is necessary to wait for multiple threads to complete tasks before the main thread can continue to perform business functions. In this business scenario, you can usually use the join method of the Thread class to let the main After the thread waits for the execution of the joined thread, the main thread can continue to execute. Of course, it can also be done using the message communication mechanism between threads. In fact, the Java concurrency tool class provides us with a tool class like "countdown", which can easily complete the business scenario mentioned.

Usage example:

public class CountDownLatchDemo {
private static CountDownLatch startSignal = new CountDownLatch(1);
//用来表示裁判员需要维护的是6个运动员
private static CountDownLatch endSignal = new CountDownLatch(6);

public static void main(String[] args) throws InterruptedException {
    ExecutorService executorService = Executors.newFixedThreadPool(6);
    for (int i = 0; i < 6; i++) {
        executorService.execute(() -> {
            try {
                System.out.println(Thread.currentThread().getName() + " 运动员等待裁判员响哨!!!");
                startSignal.await();
                System.out.println(Thread.currentThread().getName() + "正在全力冲刺");
                endSignal.countDown();
                System.out.println(Thread.currentThread().getName() + "  到达终点");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
    System.out.println("裁判员发号施令啦!!!");
    startSignal.countDown();
    endSignal.await();
    System.out.println("所有运动员到达终点,比赛结束!");
    executorService.shutdown();
}
}
输出结果:

pool-1-thread-2 运动员等待裁判员响哨!!!
pool-1-thread-3 运动员等待裁判员响哨!!!
pool-1-thread-1 运动员等待裁判员响哨!!!
pool-1-thread-4 运动员等待裁判员响哨!!!
pool-1-thread-5 运动员等待裁判员响哨!!!
pool-1-thread-6 运动员等待裁判员响哨!!!
裁判员发号施令啦!!!
pool-1-thread-2正在全力冲刺
pool-1-thread-2  到达终点
pool-1-thread-3正在全力冲刺
pool-1-thread-3  到达终点
pool-1-thread-1正在全力冲刺
pool-1-thread-1  到达终点
pool-1-thread-4正在全力冲刺
pool-1-thread-4  到达终点
pool-1-thread-5正在全力冲刺
pool-1-thread-5  到达终点
pool-1-thread-6正在全力冲刺
pool-1-thread-6  到达终点
所有运动员到达终点,比赛结束!

4. Cyclic Barrier: CyclicBarrier

CyclicBarrier is also a practical tool for multi-threaded concurrency control. It has the same waiting count function as CountDownLatch , but it is more powerful than CountDownLatch .

In order to understand CyclicBarrier, here is a popular example. When a sports meeting is held, there will be running as a sport. Let’s simulate the situation when athletes enter the stadium. Assuming that there are 6 tracks, at the beginning of the competition, 6 athletes are required to stand at the starting point at the beginning of the competition. The referee can only start running after blowing the whistle. The starting point of the runway is equivalent to the "barrier", which is the critical point , and these 6 athletes are analogous to threads, that is, these 6 threads must reach the designated point, which means that a wave can be gathered before the execution can continue. Otherwise, Each thread has to block and wait until a wave is gathered. Cyclic means cyclic, which means that CyclicBarrier is still valid after multiple threads have made up a wave, and can continue to make up the next wave. The execution diagram of CyclicBarrier is as follows:

When multiple threads have reached the specified point, they can continue to execute. This is a bit like the feeling of reporting numbers. Assuming that 6 threads are equivalent to 6 athletes, the numbers will be reported for statistics at the beginning of the track. If it happens to be 6, this wave will be collected and can be executed.

After CyclicBarrier is used once, the following is still valid and can continue to be used as a counter. This is one of the differences from CountDownLatch.

The 6 threads here, that is, the initial value of the counter, 6, are passed in through the CyclicBarrier construction method.

Main method:

//等到所有的线程都到达指定的临界点
await() throws InterruptedException, BrokenBarrierException 

//与上面的await方法功能基本一致,只不过这里有超时限制,阻塞等待直至到达超时时间为止
await(long timeout, TimeUnit unit) throws InterruptedException, 
BrokenBarrierException, TimeoutException 

//获取当前有多少个线程阻塞等待在临界点上
int getNumberWaiting()

//用于查询阻塞等待的线程是否被中断
boolean isBroken()

    
//将屏障重置为初始状态。如果当前有线程正在临界点等待的话,将抛出BrokenBarrierException。
void reset()

Comparison of CountDownLatch and CyclicBarrier:

CountDownLatch and CyclicBarrier are both tool classes used to control concurrency . Both can be understood as maintaining a counter, but the two still have different focuses:

  1. CountDownLatch is generally used for a thread A to wait for several other threads to perform tasks before it executes; and CyclicBarrier is generally used for a group of threads to wait for each other to a certain state, and then this group of threads execute at the same time; CountDownLatch emphasizes a thread Wait for multiple threads to complete something. CyclicBarrier is that multiple threads wait for each other, wait for everyone to complete, and then work together.
  2. After calling the countDown method of CountDownLatch, the current thread will not be blocked and will continue to execute; and calling the await method of CyclicBarrier will block the current thread until all the threads specified by CyclicBarrier have reached the specified point. carried out;
  3. The CountDownLatch method is relatively small, the operation is relatively simple, and CyclicBarrier provides more methods, such as getNumberWaiting(), isBroken() these methods to obtain the current status of multiple threads, and the construction method of CyclicBarrier can be passed in barrierAction , specify when Business functions executed when all threads arrive;
  4. CountDownLatch cannot be reused , while CyclicLatch can be reused .

 

 

Guess you like

Origin blog.csdn.net/ScorpC/article/details/113929960