CountDownLatch and CyclicBarrier usage scenarios

I believe that every Java developer who wants to know more about multi-threaded development will encounter CountDownLatch and CyclicBarrier. You also see various introduction principles, codes, and their differences (for interviews) on the Internet, but they rarely can explain clearly: What are their functions, how to use them, and those scenarios? Why do you always meet in an interview? This article combines scenarios to deepen your understanding.

java

CountDownLatch is a synchronous auxiliary class that allows one or more threads to wait for the other group of threads to complete the operation before continuing.

CyclicBarrier is a synchronous auxiliary class that allows a group of threads to wait for each other, reach a common point, and then continue execution.

They are all: Synchronization aid. I translate it into a synchronization aid. Since it is an aid, how to use it? Which scenes are you using?

Personal understanding: CountDownLatch: I understand him as a countdown lock

Scenario restoration: the first grade final exam is about to begin. The invigilator handed out the test papers, and then sat next to the podium playing with mobile phones while waiting for the students to answer the questions. Some students handed in the test papers in advance and set up an appointment to play ball, waiting until the last student handed in the papers , The teacher began to sort out the test papers, put up seals, got off work, and went with his wife and children.

Supplementary scenario: When we play LOL League of Legends, there will be ten different loading states, but the last one cannot load 100% due to various reasons, so the game system automatically waits for all players to be ready before displaying the game screen. Recommendation: Java advanced video resources

Understand the usage scenarios of CountDownLatch and CyclicBarrier in seconds
After each passenger (thread) gets on the bus, the available seats are reduced by 1 until it is 0, and the old driver starts to leave.

Personal understanding: CyclicBarrier: can be seen as an obstacle, all threads must be together to pass this obstacle

Scene restoration: In the past, the company organized outdoor development activities to help team building. One of the most important projects was that all employees (including female colleagues, BOSS) reached a four-meter high wall without any grasping points when completing other projects. All were required. People, one must cross the high wall before proceeding with other projects.

Recommended

Leave a Reply

Your email address will not be published.