9.常用的辅助类(必会)
9.1 CountDownLatch
package test02;
import java.util.concurrent.CountDownLatch;
//计数器
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//总数是6
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i <= 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"--->leave");
countDownLatch.countDown();//数量 -1
},String.valueOf(i)).start();
}
countDownLatch.await(); //等待计数器归零,然后再向下执行
System.out.println("Close door");
}
}
原理
countDownLatch.countDown(); //数量-1
countDownLatch.await(); //等待计数器归零,然后再向下执行
每次由线程调用countDown() 数量-1,假設计数器变为0,countDownLatch.await()就会被唤醒,继续执行!
9.2 CyclicBarrier
- 加法计数器
package test02;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclicBarrierTest {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("召唤神龙成功!");
});
for (int i = 1; i <= 7; i++) {
final int temp=i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"收集"+temp+"个龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
9.3 Semaphore
package test02;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
//线程数量 停车位
Semaphore semaphore = new Semaphore(3);
for (int i = 1; i <= 6 ; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到车位");
TimeUnit.SECONDS.sleep(2);
System.out.println(Thread.currentThread().getName()+"离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();//释放
}
},String.valueOf(i)).start();
}
}
}
原理:
semaphore.acquire();获得,假設如果已经满了,等待,等待被释放为止
semaphore.release(); 释放,会将当前的信号量释放+1,然后唤醒等待的线程
作用
多个共享资源互斥的使用!并发限流,控制最大的线程数!
本文介绍了三种常用的并发控制工具:CountDownLatch、CyclicBarrier和Semaphore。CountDownLatch用于线程同步,使主线程等待所有子线程完成;CyclicBarrier允许一组线程等待彼此到达某个屏障点;Semaphore则用于限制同时访问特定资源的线程数量,实现并发限流。通过示例代码详细解释了它们的工作原理和使用场景。
428

被折叠的 条评论
为什么被折叠?



