CountDownLatch --
CyclicBarrier ++
Semaphore -- 资源不足
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoneDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
Semaphore semaphore = new Semaphore(3);//3个停车位
for(int i = 1; i <= 6; i++) {
//模拟6个汽车
new Thread(()-> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() +"\t抢到车位");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +"\t离开车位");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class CountDownLatchDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
CountDownLatch countDownLatch = new CountDownLatch(6);
final Executor executor = Executors.newCachedThreadPool();
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{System.out.println(Thread.currentThread().getName());});
for(int i = 1; i<=6;i++) {
executor.execute(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+"\t国,被灭");
countDownLatch.countDown();
}
});
}
try {
countDownLatch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("主线程完成了");
}
}
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class CyclcBarrierDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{System.out.println("成功啦");});
for(int i = 1; i <= 7; i++) {
final int tempInt = i;
new Thread(()->{
System.out.println(Thread.currentThread().getName()+"\t收集到第第"+tempInt+"龙珠");
try {
cyclicBarrier.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BrokenBarrierException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
},String.valueOf(i)).start();
}
}
}