JUC强大的辅助类
JUC強大的輔助類
1.減少計數CountDownLatch
2.循環柵欄CyclicBarrier
3.信號燈Semaphore
減少計數CountDownLatch演示
package juc;
import java.util.concurrent.CountDownLatch;
//演示 CountDownLatch
public class CountDownLatchDemo {
? ? //6個同學陸續離開教室之后,班長鎖門
? ? public static void main(String[] args) throws InterruptedException {
? ? ? ? //創建CountDownLatch對象,設置初始值
? ? ? ? CountDownLatch countDownLatch = new CountDownLatch(6);
? ? ? ? //6個同學陸續離開教室之后
? ? ? ? for (int i=1; i <=6; i++) {
? ? ? ? ? ? new Thread(()->{
? ? ? ? ? ? ? ? System.out.println(Thread.currentThread().getName()+"號同學離開了教室");
? ? ? ? ? ? ? ? //計數 -1
? ? ? ? ? ? ? ? countDownLatch.countDown();
? ? ? ? ? ? },String.valueOf(i)).start();
? ? ? ? }
? ? ? ? //等待(變為0等待結束)
? ? ? ? countDownLatch.await();
? ? ? ? System.out.println(Thread.currentThread().getName()+"班長鎖門走人了");
? ? }
}
循環柵欄CyclicBarrier演示
package juc;
import java.util.concurrent.CyclicBarrier;
//集齊7顆龍珠就可以召喚神龍
public class CyclicBarrierDemo {
? ? //創建固定值
? ? private static final int NUMBER = 7;
? ? public static void main(String[] args) {
? ? ? ? //創建CyclicBarrier
? ? ? ? CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER, ()->{
? ? ? ? ? ? System.out.println("集齊7顆龍珠就可以召喚神龍");
? ? ? ? });
? ? ? ? //集齊7顆龍珠過程
? ? ? ? for (int i=1; i <=7; i++) {
? ? ? ? ? ? new Thread(()->{
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? System.out.println(Thread.currentThread().getName()+"龍珠被收集到了");
? ? ? ? ? ? ? ? ? ? //等待
? ? ? ? ? ? ? ? ? ? cyclicBarrier.await();
? ? ? ? ? ? ? ? } catch (Exception e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? },String.valueOf(i)).start();
? ? ? ? }
? ? }
}
信號燈Semaphore演示
package juc;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
//6輛汽車,停3個車位
public class SemaphoreDemo {
? ? public static void main(String[] args) {
? ? ? ? //創建Semaphore,設置許可數量
? ? ? ? Semaphore Semaphore = new Semaphore(3);
? ? ? ? //模擬6輛汽車
? ? ? ? for (int i=1; i <=6; i++) {
? ? ? ? ? ? new Thread(()->{
? ? ? ? ? ? ? ? try {
? ? ? ? ? ? ? ? ? ? //搶占
? ? ? ? ? ? ? ? ? ? Semaphore.acquire();
? ? ? ? ? ? ? ? ? ? System.out.println(Thread.currentThread().getName()+"搶到了車位");
? ? ? ? ? ? ? ? ? ? //設置隨機停車時間
? ? ? ? ? ? ? ? ? ? TimeUnit.SECONDS.sleep(new Random().nextInt(5));
? ? ? ? ? ? ? ? ? ? System.out.println(Thread.currentThread().getName()+"離開了車位");
? ? ? ? ? ? ? ? } catch (InterruptedException e) {
? ? ? ? ? ? ? ? ? ? e.printStackTrace();
? ? ? ? ? ? ? ? } finally {
? ? ? ? ? ? ? ? ? ? //釋放
? ? ? ? ? ? ? ? ? ? Semaphore.release();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? },String.valueOf(i)).start();
? ? ? ? }
? ? }
}
總結
- 上一篇: 我从来都不想默默无为,要有所作为就要搞点
- 下一篇: 10套精美而实用的CSS3按钮