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();
}
}
}