1、 Semaphore信号量共享锁,创建锁时传入的参数代表一次放行几个线程。下边的例子模拟了排队进厕所的场景,保安一次放行2个人进去蹲坑
private void semDemo() {
Semaphore semaphore = new Semaphore(2);
for (int i = 0; i < 8; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "开始蹲坑");
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}, "编号" + i).start();
}
}
2、 CountDownLatch,另外一种共享锁,下边的例子模拟了上船的场景,一条船只能坐五个人,当人数够了五个之后就开船
private void CountDownDemo() throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
int finalI = i;
executorService.execute(() -> {
try {
Random random = new Random();
int a = random.nextInt(10000);
Thread.sleep(a);
if(countDownLatch.getCount() <= 0){
System.out.println("乘客" + finalI + "未上船,因为船已经满员开走");
} else {
System.out.println("乘客" + finalI + "已上船,耗时" + a + "毫秒");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
});
}
countDownLatch.await();
System.out.println("船已经满员,开船");
executorService.shutdown();
}