CountDownLatch
await(),进入等待的状态
countDown,计数器减一
简单例子 某些代码需要等待其他的一系列线程执行完毕后才能执行,如下实现当for循环中的线程执行完后打印出多线程执行完毕。
import java.util.concurrent.CountDownLatch;
/**
*
*/
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException{
CountDownLatch countDownLatch = new CountDownLatch(8);
new Thread(()->{
try {
countDownLatch.await();
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("多线程运行完毕!");
}).start();
for(int i=0;i<8;i++){
int finalI = i;
new Thread(()->{
try {
Thread.sleep(finalI*1000L);
}catch (InterruptedException e){
e.printStackTrace();
}finally {
countDownLatch.countDown();
}
System.out.println(Thread.currentThread().getName()+"运行完毕");
}).start();
}
}
}
运行结果
CyclicBarrier
允许一组线程相互等待达到一个共同的障碍点,之后再继续执行
和CountDownLatch的区别
CountDownLatch一般用于一个线程等待若干个其他线程执行完成任务之后,它才执行,不可重复使用;CyclicBarrier一般用于一组线程互相等待至某个状态,然后这一组线程再同时执行,可重用。
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
for (int i = 0; i<5;i++){
int finalI = i;
new Thread(()->{
try {
Thread.sleep(finalI*500L);
System.out.println(Thread.currentThread().getName()+"等待就绪");
cyclicBarrier.await();
}catch (InterruptedException e){
e.printStackTrace();
}catch (BrokenBarrierException e){
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"开始运行");
}).start();
}
}
}
运行结果:
扫描二维码关注公众号,回复:
5689086 查看本文章
Semaphore -- 信号量
控制并发数量
使用场景:接口限流
import java.util.concurrent.Semaphore;
public class SemaphoreDemo {
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(5);
for (int i = 0;i<10;i++){
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"开始运行");
Thread.sleep(5000L);
}catch (InterruptedException e){
e.printStackTrace();
}finally {
semaphore.release();
System.out.println(Thread.currentThread().getName()+"结束运行");
}
}).start();
}
}
}
运行结果:上述代码开启是个线程,但是只能同时运行五个,控制了并发数量
Exchanger
用于交换数据
它提供一个共同点,在这个同步点两个线程可以交换彼此的数据。这两个线程通过Exchange方法交换数据,如果第一个线程先执行exchange方法,它会一直等待第二个线程也执行exchange,当两个线程都达到同步点是,这两个线程可以交换数据,将本线程生成出来的数据传递给对方。因此使用Exchanger的重点是成对的线程使用exchange()方法,当有一对线程达到同步点,就会进行数据交换。因此该工具类的对象是【成对】的。
import java.util.concurrent.Exchanger;
public class ExchangerDemo {
public static void main(String[] args) {
Exchanger<String> exchanger = new Exchanger<>();
String[] strArray = {"zhangsan","lisi","wamhwu"};
for (int i= 0;i<3;i++){
int finalI = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"待交换值为:"+strArray[finalI]);
try {
String exchangerStr = exchanger.exchange(strArray[finalI]);
System.out.println(Thread.currentThread().getName()+"交换后的值为:"+exchangerStr);
}catch (InterruptedException e){
e.printStackTrace();
}
}).start();
}
}
}
运行结果:线程0和线程1成功交换数据,线程2由于没有与之交换数据的线程会进入等待状态。