多线程并发工具类
CountDownLatch,CyclicBarrier,Semaphore,Exchanger
CountDownLatch
CountDownLatch,用于一个或多个线程等待其他线程完成操作。构造器中的计数值(count)实际上就是闭锁需要等待的线程数量。这个值只能被设置一次,主线程在启动其他线程后立即调用CountDownLatch.await()方法。这样主线程的操作就会在这个方法上阻塞,直到其他线程完成各自的任务。
听到这样的描述,相信有很多读者联想到了join方法,join的工作原理是,不停检查thread是否存活,如果存活则让当前线程永远wait,直到thread线程终止,线程的this.notifyAll 就会被调用。但是join与CountDownLatch还是存在着不少区别。join必须等到整个线程结束才行,但是CountDownLatch只要等到某一条件达成即可:
public class JoinWord implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+“first work”);
}
}
public class JoinTest {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new JoinWord());
Thread t2 = new Thread(new JoinWord());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(Thread.currentThread().getName()+"second work");
}
}
Thread-0first work
Thread-1first work
mainsecond work
public class Work implements Runnable{
CountDownLatch countDownLatch;
public Work(CountDownLatch countDownLatch){
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":first work");
countDownLatch.countDown();
try {
Thread.sleep(500);
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":third work");
}
}
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(2);
Thread t1 = new Thread(new Work(countDownLatch));
Thread t2 = new Thread(new Work(countDownLatch));
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName()+“second work”);
}
}
mainsecond work
Thread-0:first work
Thread-1:first work
Thread-1:third work
Thread-0:third work
CyclicBarrier
可以实现让一组线程等待至某个状态之后再全部同时执行,且可以重用。CountDownLatch : 一个线程(或者多个), 等待另外N个线程完成某个事情之后才能执行。 CyclicBarrier : N个线程相互等待,任何一个线程完成之前,所有的线程都必须等待。相比较而言,CountDownLatch是一个倒计时计数器,CyclicBarrier是一个水闸。使用方法,通过一个int参数构造一个CyclicBarrier 。各个线程直接使用await进行等待。
public class Work1 implements Runnable{
CyclicBarrier cyclicBarrier;
public Work1(CyclicBarrier cyclicBarrier){
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+":first work");
try {
cyclicBarrier.await();
}catch (Exception e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":third work");
}
}
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(2);
Thread t1 = new Thread(new Work(countDownLatch));
Thread t2 = new Thread(new Work(countDownLatch));
t1.start();
t2.start();
System.out.println(Thread.currentThread().getName()+“second work”);
}
}
[1]: https://www.toutiao.com/a6492900998435045901/
来源:CSDN
作者:Java开发小猿
链接:https://blog.csdn.net/weixin_36756317/article/details/103570930