在项目中看到用到了CountDownLatch和CyclicBarrier,这两个作用非常相似,这里写一些demo区分一下两者和熟悉一下API。
1.CountDownLatch的使用
描述: CountDownLatch是同步辅助工具类,允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。
API:
CountDownLatch(int count) 构造方法,参数count为计数的大小。
void await() 阻塞当前线程,如果计数为0则继续执行。
void countDown() 计数-1。
await(long timeout, TimeUnit unit) 在await()添加了超时,如果超时即使count != 0 也会继续执行。
long getCount() 获取当前计数的值。
demo:
1.单个线程被阻塞时
package com.juc;
import com.sun.org.glassfish.gmbal.ManagedObjectManager;
import org.springframework.util.StopWatch;
import java.util.concurrent.*;
/**
* @Author halon
* @create 2021/9/2
*/
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//create a thread pool with a fixed number of threads
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(6);
singleThreadWaiting(fixedThreadPool);
//shutdown thread pool
fixedThreadPool.shutdown();
}
/**
* single thread wait
*
* @throws InterruptedException
*/
private static void singleThreadWaiting(ExecutorService fixedThreadPool) {
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
fixedThreadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " running ");
sleepForFiveSeconds();
countDownLatch.countDown();
});
}
StopWatch stopWatch = new StopWatch();
stopWatch.start();
countDownLatchAwait(countDownLatch);
stopWatch.stop();
System.out.println(stopWatch.getTotalTimeSeconds() + " seconds later " + Thread.currentThread().getName() + " was awakened");
}
/**
* countDownLatch.await()
*
* @param countDownLatch
*/
private static void countDownLatchAwait(CountDownLatch countDownLatch) {
try {
countDownLatch.await();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* countDownLatch.await(timeout,timeUnit);
*
* @param countDownLatch
*/
private static void countDownLatchAwaitTimeOut(CountDownLatch countDownLatch) {
try {
countDownLatch.await(5, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* current thread sleep 5 seconds
*/
private static void sleepForFiveSeconds() {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
控制台输出:
pool-1-thread-1 running
pool-1-thread-2 running
pool-1-thread-3 running
pool-1-thread-4 running
pool-1-thread-5 running
5.003 seconds later main was awakened
可以看动在Thread 1-5 这多个线程执行完countDown之后,被阻塞的线程才会执行后续的代码。(如果代码改成 new CountDownLatch(6); main线程会被一直阻塞)
当我们的业务需要等多个接口(方法)执行结束后在完成后续的操作,就可以使用CountDownLatch的单线程等待。
2.多个线程被阻塞时
添加方法
/**
* multiple threads waiting
*
* @throws InterruptedException
*/
private static void multipleThreadsWaiting(ExecutorService fixedThreadPool) {
CountDownLatch countDownLatch = new CountDownLatch(1);
for (int i = 0; i < 5; i++) {
fixedThreadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " await");
countDownLatchAwait(countDownLatch);
System.out.println(Thread.currentThread().getName() + " running");
});
}
sleepForFiveSeconds();
System.out.println("-------------main线程的华丽分割线-------------");
countDownLatch.countDown();
}
修改main方法
public static void main(String[] args) throws InterruptedException {
//create a thread pool with a fixed number of threads
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(6);
multipleThreadsWaiting(fixedThreadPool);
//shutdown thread pool
fixedThreadPool.shutdown();
}
控制台输出结果:
pool-1-thread-2 await
pool-1-thread-3 await
pool-1-thread-1 await
pool-1-thread-4 await
pool-1-thread-5 await
-------------main线程的华丽分割线-------------
pool-1-thread-2 running
pool-1-thread-3 running
pool-1-thread-4 running
pool-1-thread-1 running
pool-1-thread-5 running
Process finished with exit code 0
线程池里所有的线程都被阻塞,等待main线程countDown操作唤醒多个线程(类似于并发)。
总结:
CountDownLatch使用减法的形式实现计数,调用await()会阻塞当前线程,当计数为0或发成超时的时候会释放所有线程,调用countDown()方法计数会减1。count不可被重置。
2.CyclicBarrier的使用
描述: 多个线程互相等待,直到到达同一个同步点,再继续一起执行。
API:
CyclicBarrier(int count) 构造方法,参数count为计数的大小。
void await() 阻塞当前线程,如果计数为0则继续执行。
void reset() 计数重置。
await(long timeout, TimeUnit unit) 在await()添加了超时,如果超时即使count != 0 也会继续执行。
demo:
package com.juc;
import java.util.concurrent.*;
/**
* @Author halon
* @create 2021/9/2
*/
public class CyclicBarrierDemo {
//create a thread pool with a fixed number of threads
private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(6);
public static void main(String[] args) throws InterruptedException {
CyclicBarrier cyclicBarrier = new CyclicBarrier(6);
for (int i = 0; i < 5; i++) {
fixedThreadPool.execute(() -> {
System.out.println(Thread.currentThread().getName() + " await ");
cyclicBarrierAwait(cyclicBarrier);
System.out.println(Thread.currentThread().getName() + " running ");
});
}
System.out.println("-------------main线程的华丽分割线-------------");
cyclicBarrierAwait(cyclicBarrier);
//shutdown thread pool
fixedThreadPool.shutdown();
}
private static void cyclicBarrierAwait(CyclicBarrier cyclicBarrier) {
try {
cyclicBarrier.await();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* current thread sleep many seconds
*/
private static void sleepForManySeconds(int seconds) {
try {
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
控制台输出:
pool-1-thread-1 await
pool-1-thread-2 await
pool-1-thread-3 await
pool-1-thread-4 await
pool-1-thread-5 await
-------------main线程的华丽分割线-------------
pool-1-thread-1 running
pool-1-thread-5 running
pool-1-thread-4 running
pool-1-thread-3 running
pool-1-thread-2 running
总结:
CyclicBarrier也可以实现CountDownLatch的功能,在CyclicBarrier的内部也是使用的减法进行的计数,与CountDownLatch不同的是CyclicBarrier内部维护了一个index,每次调用await()时候,index = --count,当index == 0唤醒所有线程。CyclicBarrier的计数是可以被重置(reset()方法)。