countdownlatch+cyclicbarrier+semphore
countdown
class q{
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
//开启线程
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"就位");
countDownLatch.countDown();
System.out.println(Thread.currentThread().getName()+"溜了");
}).start();
}
countDownLatch.await();
System.out.println("开团");
}
}
在countdown只是传递信号,没有约束力
cyclicbarrier
class W{
public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
//自带了runnable
CyclicBarrier cyclicBarrier = new CyclicBarrier(5,
()-> System.out.println("666开团"));
for (int i = 0; i < 5; i++) {
//开启线程
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"就位");
try {
cyclicBarrier.await();
System.out.println(Thread.currentThread().getName()+"溜了");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}
}).start();
}
System.out.println("开团");
}
}
这个是有约束了,await就等到集齐,才可以往下走
sempaphore
class cc{
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i < 6; i++) {
new Thread(()->{
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+"抢到女人了");
Thread.sleep(11);
System.out.println("离开");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
;
}).start();
}
}
}
很方便,适用于多个共享资源