Use and comparison of countdownlatch and cyclicbarrier in Java

Countdownlatch and cyclicbarrier are both Java 1 5 began to introduce a tool used in multithreaded programming. They have very similar purposes and are very easy to be confused.

CountDownLatch

Countdownlatch is used to make a thread wait for other n threads to execute. It is blocked until the execution of the other n threads ends (call countdown()). The other n threads exit after execution. For example, Lao Wang opened a night market club, and guests kept coming to dinner. He had to wait for all the guests to finish their meals before he could close. The first guest left and left directly. It has nothing to do with whether the second guest left or not. The second guest leaves after eating. The boss is the only one waiting for all the guests to leave. If the guest hasn't left after very late (Overtime), the closing is forced. The code example is as follows:

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CountDownLatchTest {

	public static void main(String[] args) throws InterruptedException {

		final CountDownLatch latch=new CountDownLatch(2);
		
		Thread t1=new Thread(){
			public void run(){
				try {
					System.out.println("第1桌客人进来吃饭...");
					Thread.sleep(2000);//模拟任务耗时
					System.out.println("第1桌客人进来吃完了...");
					latch.countDown();
				} catch (InterruptedException e) {
				}
			}
		};
		
		Thread t2=new Thread(){
			public void run(){
				try {
					System.out.println("第2桌客人进来吃饭...");
					Thread.sleep(3000);//模拟任务耗时
					System.out.println("第2桌客人进来吃完了...");
					latch.countDown();
				} catch (InterruptedException e) {
				}
			}
		};
		Thread t3=new Thread(){
			public void run(){
				try {
					System.out.println("我是店主:饭店正在营业,等客人吃完饭之后再打烊...");
					latch.await(15,TimeUnit.SECONDS);
					System.out.println("我是店主:你们已经吃完了,现在该我来收尾工作,然后打烊了...");
				} catch (InterruptedException e) {
				}
			}
		};
		t3.start();
		t1.start();
		t2.start();
	}

}

Three live simulations are enabled here, where T3 is the waiting thread and T3 calls latch await(15,TimeUnit.SECONDS); Then it starts blocking, waiting for T1 and T2 to give signals. According to the definition of the construction method, countdownlatch (2) here the count he needs to wait is 2, T1 and T2. After the execution is completed, call countdown() once respectively, and then T3 can start execution. Assuming that T2 calls sleep for 20 seconds, T3 will be forced to close because it reaches the set 15 second timeout when it cannot wait for the countdown () signal of T2.

CyclicBarrier

The function of cyclicbarrier is to make multiple threads reach the same barrier before continuing the follow-up work. In this process, the threads wait for each other. After everyone reaches the same barrier, we can continue our next work. For example, when friends have a dinner together, we propose a toast. Some people move fast, others move slowly, and those who move fast have raised their glasses, and then hold them like this. When everyone keeps pouring the glasses full, they keep raising them. Finally, when everyone lifts them, they shout: dry! Then they drank separately. The barrier here is the moment when everyone raises the cup. Before that, everyone is blocked and doing their own things to each other. Only when everyone finishes raising their glasses and reaches the consistent barrier, can everyone shout: cheers. Code examples are as follows:

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CycleBarrierTest {

	public static void main(String[] args) {

		final CyclicBarrier cb=new CyclicBarrier(3);
		
		
		Thread t1=new Thread(){
			public void run(){
				try {
					Thread.sleep(2000);
					System.out.println("张三说:我的杯子已经端起来了");
					cb.await();
					System.out.println("张三说:干!");
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					e.printStackTrace();
				}
			}
		};
		
		Thread t2=new Thread(){
			public void run(){
				try {
					Thread.sleep(3000);
					System.out.println("李四说:我的杯子已经端起来了");
					cb.await();
					System.out.println("李四说:干!");
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					e.printStackTrace();
				}
			}
		};
		
		Thread t3=new Thread(){
			public void run(){
				try {
					Thread.sleep(1000);
					System.out.println("王五说:我的杯子已经端起来了");
					cb.await();
					System.out.println("王五说:干!");
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (BrokenBarrierException e) {
					e.printStackTrace();
				}
			}
		};
		
		t1.start();
		t2.start();
		t3.start();
		
	}

}

It can be seen from the running result sequence that Wang Wuxian raised the cup, did not execute it downward, and printed "dry". But after everyone raised it, they said "dry" together. Here is the effect of cyclicbarrier. From the cyclicbarrier (3) function, we can see that the initialization count is 3, and we need to wait for three counts. If only one count is not reached, it will be blocked all the time. If we change 3 to 4, we will find that the program cannot finish execution, but will be blocked all the time.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>