CountDownLatch的例子:
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i = 0; i < 7; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName() +"=====卷王下班了");
countDownLatch.countDown();
},i+"").start();
}
try {
countDownLatch.await();
System.out.println(Thread.currentThread().getName() +" 物业关门");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
CyclicBarrier例子:
public static void main(String[] args) {
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{
System.out.println(Thread.currentThread().getName()+"开始出发了...");
});
for (int i = 0; i < 7; i++) {
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"===卷王了,");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
},String.format("%s",i)).start();
}
}
Semaphore例子:
public static void main(String[] args) {
// 抢车位
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 9; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"... 开进来了");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"... 开走了");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}