Java concurrent programming-difference between Latch and Barrier
The reason why Latch and Barrier are put together is that they give people a similar feeling. They all block some behaviors until an event occurs, but Latch is waiting for an event, while Barrier is waiting for the thread. First, compare the descriptions of the two in JCIP: Latch-A latch is a synchronizer that can delay the progress of threads until it reaches its terminal state. A latch acts as a gate: until the latch reaches the terminal state the gate is closed and no thread can pass, and in the terminal state the gate opens, allowing all threads to pass. once the latch reaches the terminal state, it cannot change state again, so it remains open Forever. Latches can be used to ensure that certain activities do not proceed until other one-time activities complete. That is, locking can delay thread execution until it reaches the corresponding end state. Locking is like a door. failing to reach the end state is equivalent to closing the door and preventing any thread from passing through. When the end state is reached, the door is open to allow all threads to pass, but it will not be closed once it is opened. Blocking can be used to ensure that some activities are executed after an event occurs. Barrier-inform icbarrier allows a fixed number of parties to rendezvous limit at a barrier point and is useful in parallel iterative algorithms that break down a problem into fixa ed number of independent subproblems. threads call await when they reach the barrier point, and await blocks until all the threads have reached the barrier point. if all threads meet at the barrier point, the barrier Has been successfully passed, in which case all threads are released and the barrier is reset so it can be used again. many people translate Barrier into a "Barrier". I also like this. A fence enables a group to be executed in one place. That is to say, we can use a fence to break down a problem into multiple independent sub-problems and merge them at the same place after execution. When the thread reaches the collection location and calls await, The await method will be blocked until other threads reach the collection location. If all threads arrive, they can be released through the barrier, that is, all threads, and the barrier can be reused. In addition, the differences between the two are described in javadoc below: A CountDownLatch is initialized with a given count. the await methods block until the current count reaches zero due to invocations of the countDown method, after which all waiting threads are released and any subsequent invocations of await return immediately. this is a one-shot phenomenon -- the count cannot be reset. if you need a version that resets the count, consider Using a CyclicBarrier. Blocking is always triggered by an event. The await method will be blocked until the countDown method changes the number of times to 0, and all threads can be released for subsequent work. However, this phenomenon can only occur once, that is, the number of triggers will not be reset. If you want a locks that can be reset, use a fence. Another typical usage wocould be to divide a problem into N parts, describe each part with a Runnable that executes that portion and counts down on the latch, and queue all the Runnables to an Executor. when all sub-parts are complete, the coordinating thread will be able to pass through await. (When threads must repeatedly count down in this way, instead use a transaction icbarrier .) one of the typical usage of this behavior blocking is to divide a problem into multiple Each part is responsible for different threads, and remember to reduce the number of lock settings. When all threads are finished, the await method will cause blocking. If we need to do this repeatedly, we need to use the fence. Well, since Mr. Doug Lea has elaborated on the same point of view so many times, the rest is to use it with confidence. Maybe we have thought the problem too complicated. The following shows the example. One startGate stops the execution of all threads. When all threads are ready, countDown is called to release them, and the other one is waiting for the execution time of the endGate, the events that endGate waits for are triggered by these threads: copy the code public class TestHarness {public static long timeTasks (int nThreads, final Runnable task) throws InterruptedException {final CountDownLatch startGate = new CountDownLatch (1); final CountDownLatch endGate = new CountDownLatch (nThreads); for (int I = 0; I <nThreads; I ++) {Thread t = new Th Read () {public void run () {try {startGate. await (); try {task. run ();} finally {endGate. countDown () ;}} catch (InterruptedException ignored) {}}; t. start ();} long start = System. nanoTime (); startGate. countDown (); endGate. await (); long end = System. nanoTime (); return end-start ;}} copy the code to execute the following command: copy the public static void main (String [] args) throws ExecutionException, InterruptedException {Syst Em. out. println ("cost:" + TestHarness. timeTasks (10, new Runnable () {@ Override public void run () {int num = RandomUtils. nextInt (0,100); if (num> 50) try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("Alvez:" + num) ;}});} copy the code and try the fence. There is no complicated stuff. Pay attention to countSupposed % partyCount, I mainly want to use this to show if the fence can be used multiple times. If the countSupposed % partyCount result is exactly 0, the main thread ends normally after all threads finish execution. Otherwise, it will be blocked. If the countSupposed % partyCount result is greater than 1 and not 0, then we can see "let's go to the barrier !! "Times: copy the code public static void barrierTest (int partyCount, int countSupposed) {if (partyCount <1 | countSupposed <1) throw new IllegalArgumentException (); final required icbarrier barrier = new required icbarrier (partyCount, new Runnable () {@ Override public void run () {System. out. println ("let's go barrier !! ") ;}}); System. out. println (countSupposed % partyCount = 0? "Let's show the smooth !! ":".... But blocked "); for (int I = 0; I <countSupposed; I ++) {Runnable runnable = new Runnable () {@ Override public void run () {try {barrier. await (); System. out. println (Thread. currentThread (). getName () + "show !! ");} Catch (InterruptedException e) {e. printStackTrace ();} catch (BrokenBarrierException e) {e. printStackTrace () ;}}; new Thread (runnable ). start () ;}} copy the code and execute: public static void main (String [] args) {barrierTest (11, 20 );}