只要用在两种方法:多线程共享资源互斥!并发线程控制
public class CountDownLatchDemo {
public static void main(String[] args) throws InterruptedException {
//CountDownLatch 默认的初始化
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 6; i++) {
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "start");
countDownLatch.countDown();//计算器 -1
}, String.valueOf(i)).start();
}
countDownLatch.await();// 只要计算器没有归零、我们就一直阻塞 会阻塞等待计数器归零 当计数器变为0的时候,就会方向
//等待上面的六个线程跑完执行 end
System.out.println(Thread.currentThread().getName() + "end");
}
public class CyclicBarrierDemo {
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println("收集成功");
});
for (int i = 0; i < 7; i++) {
final int tempInt= i;
new Thread(() -> {
System.out.println(Thread.currentThread().getName()+"收集"+tempInt+"颗");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
public class SemaphoreDemo {
public static void main(String[] args) {
//模拟车位
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i <6; i++) {
new Thread(() -> {
try {
semaphore.acquire();//得到 当一个线程调用操作的时候、就是获取到了一个新号量-1、如果当前wei0,就会一直等待下去
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();
}
}
}