CountDownLatch
减法计数器
countDownLatch.await()
: 等待计数器归零,然后在向下执行
countDownLatch.countDown()
:数量减1
package collection;
import java.util.concurrent.CountDownLatch;
/**
* 计数器
*/
public class CountDownLatchTest {
public static void main(String[] args) throws Exception{
//总数为6
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"go out");
countDownLatch.countDown(); // -1
},String.valueOf(i)).start();
}
countDownLatch.await(); //等待计数器归零,然后在向下执行
System.out.println("关门");
}
}
CyclicBarrier
加法计数器
package collection;
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 = 0; i < 7; i++) {
// lambda 能操作到 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();
}
}
}
Semaphore
信号量
package collection;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* @author admin
* @version 1.0.0
* @ClassName SemaphoreTest.java
* @Description TODO
* @createTime 2021年05月16日 21:18:00
*/
public class SemaphoreTest {
public static void main(String[] args) {
//线程数量 停车位 限流
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 6; i++) {
new Thread(()->{
//acquire() 得到
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 {
//release() 释放
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
原理:
semaphore.acquire()
:获得,假设已经满了,等待,等待被释放为止。
semaphore.release()
:释放,会将当前的信号量释放+1,然后唤醒等待的线程。
作用
:
- 多个共享资源互斥的使用。
- 并发限流,控制最大的线程数