In previous articles, we introduced the tools for concurrent programming in Java: BlockingQueue interface, ArrayBlockingQueue, DelayQueue, LinkedBlockingQueue, PriorityBlockingQueue, SynchronousQueue, BlockingDeque interface ConcurrentHashMap, CountDownLatch. This is the tenth article in the series.

Java. Util. Concurrent. CyclicBarrier provides a multithreaded synchronization waiting for each other, can understand it’s an obstacle, all threads to reach this obstacle will be will be in a wait state, reaches the obstacle until all threads, all threads to continue.

For example, a CyclicBarrier is similar to a group of friends who arrange to travel and meet at the entrance of a scenic spot. The entrance is a Barrier and wait for everyone to arrive before entering the scenic spot. After entering the scenic spot, we went to climb the mountain, some people climb fast, some people climb slowly, we arranged to meet at the top of the mountain, so the top of the mountain is another Barrier, waiting for everyone to reach the top of the mountain before going down together.

Here’s a picture to illustrate the problem.Each thread calls await(), inCyclicBarrierObstacles “wait for each other” once all threads have arrivedCyclicBarrier(All calledCyclicBarrierMethod), all threads will be woken up again together to continue execution.

1. Create a CyclicBarrier

When you create a CyclicBarrier, you specify how many thread synchronizations you want to control. For example, the CyclicBarrier below is set to control synchronization between two threads.

CyclicBarrier barrier = new CyclicBarrier(2);
Copy the code

2. Wait at CyclicBarrier

The wait state is entered by calling the await() method of CyclicBarrier, which is usually called after the thread has completed its periodic task.

barrier.await();
Copy the code

CyclicBarrier also provides another way to specify the duration of the wait timeout, after which the thread will automatically wake up to continue execution even if there is no other thread calling the await method. (My friends made an appointment to travel. After 10 minutes, YOU didn’t come, SO I went first.)

barrier.await(10, TimeUnit.SECONDS);
Copy the code

The waiting threads waits at theCyclicBarrieruntil either:

The thread waiting at the CyclicBarrier is released and execution continues (if any of the following conditions are met)

  • The last arriving thread calls the await() method
  • This thread is interrupted by another thread that calls its interrupt() method.
  • Another thread in the wait state was interrupted
  • The other thread in the wait state is inCyclicBarrierTimed out while waiting at.
  • Some external thread calledCyclicBarrier.reset()Remove barriers.

3. CyclicBarrier Action

CyclicBarrier actions are relatively difficult to understand and can be understood as the behavior of the barrier itself. This Action is a thread that will be executed after all threads have reached the barrier.

Runnable barrierAction = Create thread; CyclicBarrier barrier = new CyclicBarrier(2, barrierAction);Copy the code

If this code still doesn’t understand the CyclicBarrier Action, take a look at the following example.

4. The CyclicBarrier example

The following code demonstrates how to use CyclicBarrier for thread synchronization:

Runnable barrier1Action = new Runnable() {public void run() {system.out.println (" barrier1Action = new Runnable() {public void run() {system.out.println (" }}; Runnable barrier2Action = new Runnable() {public void run() {system.out.println (" barrier2Action = new Runnable() {public void run() {system.out.println ("); }}; // CyclicBarrier barrier1 = new CyclicBarrier(2, barrier1Action); // CyclicBarrier barrier2 = new CyclicBarrier(2, barrier2Action); Cyclicbarrierrunnable1 = new CyclicBarrierRunnable(barrier1, barrier2); CyclicBarrierRunnable(barrier1, barrier2); CyclicBarrierRunnable(barrier1, barrier2) = new CyclicBarrierRunnable(barrier1, barrier2); new Thread(barrierRunnable1).start(); // A, thread-0 new Thread(barrierRunnable2).start(); // Visitor B, Thread-1Copy the code

The following is a thread class CyclicBarrierRunnable, starting one represents one visitor

public class CyclicBarrierRunnable implements Runnable{ CyclicBarrier barrier1 = null; CyclicBarrier barrier2 = null; Public CyclicBarrier (CyclicBarrier barrier1,CyclicBarrier barrier2) {this.barrier1 = barrier1; this.barrier2 = barrier2; } public void run() { try { Thread.sleep(1000); System.out.println(thread.currentThread ().getName() + "reach the destination "); this.barrier1.await(); Thread.sleep(1000); System.out.println(thread.currentThread ().getName() + "climb to the top "); this.barrier2.await(); System.out.println(thread.currentThread ().getName() +" ); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); }}}Copy the code

The output below is the printed result of the execution of the code above. After executing the code above for several times, it will be found that the order of arrival of Thread-0 and Thread-1 at obstacle 1 and obstacle 2 is uncertain, but the first one will always arrive and the second one will be executed.

Thread-0 is at the gate of the attraction Thread-1 is at the gate of the attraction Thread-1 is at the gate of the attraction Thread-1 is at the gate of the attraction Thread-1 is at the gate of the attraction Thread-1 is at the gate of the attraction Thread-1 is at the gate of the attraction Thread-0 is at the top of the hill Thread-0 is at the top of the hill Thread-0 is at the top of the hill Thread-0 is at the top of the hill Go home down the mountain! Thread-1 had a good time. Go back down the hill!Copy the code

Welcome to my blog, where there are many fine collections

  • This article is reprinted with a credit (must be accompanied by a link, not only the text) : Antetokounmpo blog.

Feel helpful to you, help me like, share! Your support is my inexhaustible creative power! . In addition, the author recently a period of time output as follows boutique content, looking forward to your attention.

  • Spring Boot2.0 by Hand
  • Spring Security- JWT-OAUTH2
  • RBAC Authority Management System for Actual Combat Front-end and Back-end Separation
  • “Actual SpringCloud Micro-service from Bronze to King”
  • VUE Series