JUC 常用3大辅助类
CountDownLatch
充当计数器作用 每次执行减一
使用await方法 判断必须值为0时才能下一步操作
package com.jie.add;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//总数是6
CountDownLatch countDownLatch=new CountDownLatch(6);
//countDownLatch.countDown();//-1
for (int i = 0; i < 6; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+" run");
countDownLatch.countDown();
}).start();
}
countDownLatch.await();//等值为0时才能向下走
System.out.println("运行完辣");
}
}
CyclicBarrierTest
上面对应的减法,这个就是对应的加法
public static void main(String[] args) {
CyclicBarrier cyclicBarrier=new CyclicBarrier(7,()->{
System.out.println("召唤神龙成功");
});
for (int i = 1; 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
用与分配资源情形
public static void main(String[] args) {
//线程数量 停车位
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i <= 6; i++) {
new Thread(()->{
//acquire 得到
//release 释放 可以理解为操作系统的PV操作
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+" 抢到车位");
TimeUnit.SECONDS.sleep(3);
System.out.println(Thread.currentThread().getName()+" 离开车位");
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
semaphore.release();
}
}).start();
}
}

浙公网安备 33010602011771号