Java concurrent programming: CountDownLatch, CyclicBarrier and Semaphore

高洛峰
Release: 2016-10-15 14:03:23
Original
1927 people have browsed it

In Java 1.5, some very useful auxiliary classes are provided to help us with concurrent programming, such as CountDownLatch, CyclicBarrier and Semaphore. Today we will learn the usage of these three auxiliary classes.

The following is the outline of the content of this article:

1. CountDownLatch usage

2. CyclicBarrier usage

3. Semaphore usage

1. CountDownLatch usage

The CountDownLatch class is located under the java.util.concurrent package. You can use it to achieve something like Counter function. For example, there is a task A that has to wait for the other four tasks to complete before it can be executed. At this time, you can use CountDownLatch to implement this function.

The CountDownLatch class only provides one constructor:

public CountDownLatch(int count) { }; //参数count为计数值
Copy after login

Then the following three methods are the most important methods in the CountDownLatch class:

public void await() throws InterruptedException { }; //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行 public boolean await(long timeout, TimeUnit unit) throws InterruptedException { }; //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行 public void countDown() { }; //将count值减1
Copy after login

Let’s look at an example below to understand the usage of CountDownLatch:

public class Test { public static void main(String[] args) { final CountDownLatch latch = new CountDownLatch(2); new Thread(){ public void run() { try { System.out.println("子线程"+Thread.currentThread().getName()+"正在执行"); Thread.sleep(3000); System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕"); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); new Thread(){ public void run() { try { System.out.println("子线程"+Thread.currentThread().getName()+"正在执行"); Thread.sleep(3000); System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕"); latch.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); try { System.out.println("等待2个子线程执行完毕..."); latch.await(); System.out.println("2个子线程已经执行完毕"); System.out.println("继续执行主线程"); } catch (InterruptedException e) { e.printStackTrace(); } } }
Copy after login

Execution results:

线程Thread-0正在执行 线程Thread-1正在执行 等待2个子线程执行完毕... 线程Thread-0执行完毕 线程Thread-1执行完毕 2个子线程已经执行完毕 继续执行主线程
Copy after login

Literally means loopback fence, through which a group of threads can be made to wait for a certain state and then execute them all at the same time. It is called loopback because CyclicBarrier can be reused after all waiting threads are released. Let's call this state barrier for the time being. When the await() method is called, the thread is in barrier.

The CyclicBarrier class is located under the java.util.concurrent package. CyclicBarrier provides 2 constructors:

public CyclicBarrier(int parties, Runnable barrierAction) { } public CyclicBarrier(int parties) { }
Copy after login

The parameter parties refers to how many threads or tasks are allowed to wait for the barrier state; the parameter barrierAction is executed when these threads all reach the barrier state. Content.

Then the most important method in CyclicBarrier is the await method, which has 2 overloaded versions:

public int await() throws InterruptedException, BrokenBarrierException { }; public int await(long timeout, TimeUnit unit)throws InterruptedException,BrokenBarrierException,TimeoutException { }
Copy after login

The first version is more commonly used and is used to suspend the current thread until all threads reach the barrier state and then execute subsequent tasks at the same time. ;

The second version is to let these threads wait for a certain period of time. If there are still threads that have not reached the barrier state, directly let the threads that have reached the barrier perform subsequent tasks.

Let’s take a few examples to understand:

If there are several threads that need to write data, and only after all threads have completed the data writing operation, these threads can continue to do the following things. At this time, you can use CyclicBarrier:

public class Test { public static void main(String[] args) { int N = 4; CyclicBarrier barrier = new CyclicBarrier(N); for(int i=0;i
        
Copy after login

Execution result:

线程Thread-0正在写入数据... 线程Thread-3正在写入数据... 线程Thread-2正在写入数据... 线程Thread-1正在写入数据... 线程Thread-2写入数据完毕,等待其他线程写入完毕 线程Thread-0写入数据完毕,等待其他线程写入完毕 线程Thread-3写入数据完毕,等待其他线程写入完毕 线程Thread-1写入数据完毕,等待其他线程写入完毕 所有线程写入完毕,继续处理其他任务... 所有线程写入完毕,继续处理其他任务... 所有线程写入完毕,继续处理其他任务... 所有线程写入完毕,继续处理其他任务...
Copy after login

As can be seen from the above output results, after each writing thread completes the write data operation, it is waiting for other threads to complete the write operation.

After all thread writing operations are completed, all threads will continue to perform subsequent operations.

If you want to perform additional operations after all threads have completed writing operations, you can provide Runnable parameters for CyclicBarrier:

public class Test { public static void main(String[] args) { int N = 4; CyclicBarrier barrier = new CyclicBarrier(N,new Runnable() { @Override public void run() { System.out.println("当前线程"+Thread.currentThread().getName()); } }); for(int i=0;i
        
Copy after login

Running results:

线程Thread-0正在写入数据... 线程Thread-1正在写入数据... 线程Thread-2正在写入数据... 线程Thread-3正在写入数据... 线程Thread-0写入数据完毕,等待其他线程写入完毕 线程Thread-1写入数据完毕,等待其他线程写入完毕 线程Thread-2写入数据完毕,等待其他线程写入完毕 线程Thread-3写入数据完毕,等待其他线程写入完毕 当前线程Thread-3 所有线程写入完毕,继续处理其他任务... 所有线程写入完毕,继续处理其他任务... 所有线程写入完毕,继续处理其他任务... 所有线程写入完毕,继续处理其他任务...
Copy after login

As can be seen from the results, when all four threads reach the barrier state , one thread will be selected from the four threads to execute the Runnable.

Let’s take a look at the effect of specifying the time for await:

public class Test { public static void main(String[] args) { int N = 4; CyclicBarrier barrier = new CyclicBarrier(N); for(int i=0;i
        
Copy after login

Execution results:

线程Thread-0正在写入数据... 线程Thread-2正在写入数据... 线程Thread-1正在写入数据... 线程Thread-2写入数据完毕,等待其他线程写入完毕 线程Thread-0写入数据完毕,等待其他线程写入完毕 线程Thread-1写入数据完毕,等待其他线程写入完毕 线程Thread-3正在写入数据... java.util.concurrent.TimeoutException Thread-1所有线程写入完毕,继续处理其他任务... Thread-0所有线程写入完毕,继续处理其他任务... at java.util.concurrent.CyclicBarrier.dowait(Unknown Source) at java.util.concurrent.CyclicBarrier.await(Unknown Source) at com.cxh.test1.Test$Writer.run(Test.java:58) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait(Unknown Source) at java.util.concurrent.CyclicBarrier.await(Unknown Source) at com.cxh.test1.Test$Writer.run(Test.java:58) java.util.concurrent.BrokenBarrierException at java.util.concurrent.CyclicBarrier.dowait(Unknown Source) at java.util.concurrent.CyclicBarrier.await(Unknown Source) at com.cxh.test1.Test$Writer.run(Test.java:58) Thread-2所有线程写入完毕,继续处理其他任务... java.util.concurrent.BrokenBarrierException 线程Thread-3写入数据完毕,等待其他线程写入完毕 at java.util.concurrent.CyclicBarrier.dowait(Unknown Source) at java.util.concurrent.CyclicBarrier.await(Unknown Source) at com.cxh.test1.Test$Writer.run(Test.java:58) Thread-3所有线程写入完毕,继续处理其他任务...
Copy after login

The above code deliberately delays the start of the last thread in the for loop of the main method because after the first three threads have reached the barrier , after waiting for the specified time and finding that the fourth thread has not reached the barrier, an exception is thrown and the subsequent tasks continue to be executed.

In addition, CyclicBarrier can be reused. Take a look at the following example:

public class Test { public static void main(String[] args) { int N = 4; CyclicBarrier barrier = new CyclicBarrier(N); for(int i=0;i
        
Copy after login

Execution result:

线程Thread-0正在写入数据... 线程Thread-1正在写入数据... 线程Thread-3正在写入数据... 线程Thread-2正在写入数据... 线程Thread-1写入数据完毕,等待其他线程写入完毕 线程Thread-3写入数据完毕,等待其他线程写入完毕 线程Thread-2写入数据完毕,等待其他线程写入完毕 线程Thread-0写入数据完毕,等待其他线程写入完毕 Thread-0所有线程写入完毕,继续处理其他任务... Thread-3所有线程写入完毕,继续处理其他任务... Thread-1所有线程写入完毕,继续处理其他任务... Thread-2所有线程写入完毕,继续处理其他任务... CyclicBarrier重用 线程Thread-4正在写入数据... 线程Thread-5正在写入数据... 线程Thread-6正在写入数据... 线程Thread-7正在写入数据... 线程Thread-7写入数据完毕,等待其他线程写入完毕 线程Thread-5写入数据完毕,等待其他线程写入完毕 线程Thread-6写入数据完毕,等待其他线程写入完毕 线程Thread-4写入数据完毕,等待其他线程写入完毕 Thread-4所有线程写入完毕,继续处理其他任务... Thread-5所有线程写入完毕,继续处理其他任务... Thread-6所有线程写入完毕,继续处理其他任务... Thread-7所有线程写入完毕,继续处理其他任务...
Copy after login

It can be seen from the execution result that after the first four threads cross the barrier state, they can be used for a new round. use. CountDownLatch cannot be reused.

3. Semaphore usage

Semaphore is translated literally as semaphore. Semaphore can control the number of threads accessed at the same time, obtain a permission through acquire(), wait if not, and release() to release a permission.

The Semaphore class is located under the java.util.concurrent package. It provides 2 constructors:

public Semaphore(int permits) { //参数permits表示许可数目,即同时可以允许多少线程进行访问 sync = new NonfairSync(permits); } public Semaphore(int permits, boolean fair) { //这个多了一个参数fair表示是否是公平的,即等待时间越久的越先获取许可 sync = (fair)? new FairSync(permits) : new NonfairSync(permits); }
Copy after login

Let’s talk about some of the more important methods in the Semaphore class. The first is the acquire() and release() methods:

public void acquire() throws InterruptedException { } //获取一个许可 public void acquire(int permits) throws InterruptedException { } //获取permits个许可 public void release() { } //释放一个许可 public void release(int permits) { } //释放permits个许可
Copy after login

acquire() is used to obtain a permission. If no permission can be obtained, it will wait until permission is obtained.

release() is used to release the permission. Note that permission must be obtained before it can be released.

These four methods will be blocked. If you want to get the execution result immediately, you can use the following methods:

public boolean tryAcquire() { }; //尝试获取一个许可,若获取成功,则立即返回true,若获取失败,则立即返回false public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { }; //尝试获取一个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false public boolean tryAcquire(int permits) { }; //尝试获取permits个许可,若获取成功,则立即返回true,若获取失败,则立即返回false public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException { }; //尝试获取permits个许可,若在指定的时间内获取成功,则立即返回true,否则则立即返回false
Copy after login

In addition, you can also get the number of available permissions through the availablePermits() method.

Let’s take a look at the specific use of Semaphore through an example:

假若一个工厂有5台机器,但是有8个工人,一台机器同时只能被一个工人使用,只有使用完了,其他工人才能继续使用。那么我们就可以通过Semaphore来实现:

public class Test { public static void main(String[] args) { int N = 8; //工人数 Semaphore semaphore = new Semaphore(5); //机器数目 for(int i=0;i
        
Copy after login

执行结果:

工人0占用一个机器在生产... 工人1占用一个机器在生产... 工人2占用一个机器在生产... 工人4占用一个机器在生产... 工人5占用一个机器在生产... 工人0释放出机器 工人2释放出机器 工人3占用一个机器在生产... 工人7占用一个机器在生产... 工人4释放出机器 工人5释放出机器 工人1释放出机器 工人6占用一个机器在生产... 工人3释放出机器 工人7释放出机器 工人6释放出机器
Copy after login

下面对上面说的三个辅助类进行一个总结:

1)CountDownLatch和CyclicBarrier都能够实现线程之间的等待,只不过它们侧重点不同:

CountDownLatch一般用于某个线程A等待若干个其他线程执行完任务之后,它才执行;

而CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行;

另外,CountDownLatch是不能够重用的,而CyclicBarrier是可以重用的。

2)Semaphore其实和锁有点类似,它一般用于控制对某组资源的访问权限。

参考资料:

《Java编程思想》

http://www.itzhai.com/the-introduction-and-use-of-a-countdownlatch.html

http://leaver.me/archives/3220.html

http://developer.51cto.com/art/201403/432095.htm

http://blog.csdn.net/yanhandle/article/details/9016329

http://blog.csdn.net/cutesource/article/details/5780740

http://www.cnblogs.com/whgw/archive/2011/09/29/2195555.html


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!