JUC —— 常用辅助类
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                JUC —— 常用辅助类
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.                        
                                CountDownLatch
允許一個(gè)或多個(gè)線程等待直到在其他線程中執(zhí)行的一組操作完成的同步輔助(減法計(jì)數(shù)器)
//計(jì)數(shù)器 public class CountDownLatchDemo {public static void main(String[] args) throws InterruptedException {//計(jì)數(shù)器總數(shù)是6,必須要執(zhí)行任務(wù)的時(shí)候再使用CountDownLatch countDownLatch = new CountDownLatch(6);//模擬6個(gè)小朋友放學(xué),全部走出班級(jí)后在關(guān)門for(int i=1;i<=6;i++){new Thread(()->{System.out.println(Thread.currentThread().getName()+" GO OUT");countDownLatch.countDown(); //-1},String.valueOf(i)).start();}countDownLatch.await(); //等待計(jì)數(shù)器歸零,然后再向下執(zhí)行System.out.println("關(guān)門");} }執(zhí)行結(jié)果:
1 GO OUT 2 GO OUT 3 GO OUT 4 GO OUT 5 GO OUT 6 GO OUT 關(guān)門CyclicBarrier
允許一組線程全部等待彼此達(dá)到共同屏障點(diǎn)的同步輔助,循環(huán)阻塞在涉及固定大小的線程方的程序中很有用,這些線程必須偶爾等待彼此,屏障被稱為循環(huán),因?yàn)樗梢栽诘却木€程被釋放之后重新使用(加法計(jì)數(shù)器)
public class CyclicBarrierTest {public static void main(String[] args) {/*** 集齊7顆龍珠召喚神龍*/CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()->{System.out.println("集齊7顆,召喚神龍");});for (int i = 1; i <= 7 ; i++) {int temp = i;new Thread(()->{System.out.println("收集第"+temp+"顆龍珠");try {cyclicBarrier.await(); //等待執(zhí)行到對(duì)應(yīng)次數(shù)的線程才執(zhí)行cyclicBarrier中的} catch (Exception e) {e.printStackTrace();}}).start();}} }執(zhí)行結(jié)果:
收集第2顆龍珠 收集第1顆龍珠 收集第3顆龍珠 收集第4顆龍珠 收集第6顆龍珠 收集第5顆龍珠 收集第7顆龍珠 集齊7顆,召喚神龍Semaphore
一個(gè)計(jì)數(shù)信號(hào)量,在概念上,信號(hào)量維持一組許可證,如果有必要,每個(gè)acquire()都會(huì)阻塞,直到許可證可用,然后才能使用它。每個(gè)release()添加許可證,潛在地釋放阻塞獲取方。但是,沒有使用實(shí)際的許可證對(duì)象,Semaphore只保留可用輸了的計(jì)數(shù),并相應(yīng)地執(zhí)行(信號(hào)量)
public class SemaphoreTest {public static void main(String[] args) {//線程數(shù)量Semaphore semaphore = new Semaphore(3);//有三輛車,搶6個(gè)停車位for (int i = 1; i <=6 ; i++) {new Thread(()->{try {//acquire() 得到semaphore.acquire();System.out.println(Thread.currentThread().getName()+"搶到車位停車");TimeUnit.SECONDS.sleep(2);System.out.println(Thread.currentThread().getName()+"離開車位");//release() 釋放semaphore.release();} catch (InterruptedException e) {e.printStackTrace();}},String.valueOf(i)).start();}} }執(zhí)行結(jié)果:
3搶到車位停車 4搶到車位停車 1搶到車位停車 4離開車位 1離開車位 3離開車位 2搶到車位停車 5搶到車位停車 6搶到車位停車 5離開車位 6離開車位 2離開車位作用:多個(gè)共享資源互斥使用。并發(fā)限流,控制最大的線程數(shù)
總結(jié)
以上是生活随笔為你收集整理的JUC —— 常用辅助类的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: pug 编译html,pug之HTML模
- 下一篇: java中Graphics类的使用
