减少计数类
package com.example.demo.test;
import java.util.concurrent.CountDownLatch;
public class eeew {
/**
* 场景: 6 个同学陆续离开教室后值班同学才可以关门。
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
CountDownLatch count = new CountDownLatch(6);
for (int i=1;i<=6;i++){
new Thread(()-> {
System.out.println(Thread.currentThread().getName()+" 号同学离开了教室");
count.countDown();
},String.valueOf(i)).start();
}
count.await();
//最后才执行这个方法
System.out.println(Thread.currentThread().getName()+" 班长锁门走人了");
}
}
循环栅栏
package com.example.demo.test;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class fff {
/**
* 场景: 集齐 7 颗龙珠就可以召唤神龙
* @param args
*/
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7, ()->{
System.out.println("召唤神龙成功! ");
});
for (int i = 1; i <= 7; i++) {
int temp = i;
//lambda 能拿到i吗
new Thread(()->{
System.out.println(Thread.currentThread().getName() + "收集" + temp + "个龙珠");
try {
cyclicBarrier.await();
System.out.println("111");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
}
}
信号量
package com.example.demo.test;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class wee {
/**
* 场景: 抢车位, 6 部汽车 3 个停车位
* @param args
*/
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(new Random().nextInt(5));
} catch (Exception e) {
e.printStackTrace();
}finally {
//释放车位
semaphore.release();
System.out.println(Thread.currentThread().getName()+"开走了");
}
},String.valueOf(i)).start();
}
}
}