JUC——辅助类
目錄
- CountDownLatch
- CyclicBarrier
- Semaphore
CountDownLatch
減少計(jì)數(shù)器
public class CountDownLatchDemo {public static void main(String[] args) throws InterruptedException{CountDownLatch countDownLatch = new CountDownLatch(6);for (int i = 1; i <=6; i++) //6個(gè)上自習(xí)的同學(xué),各自離開(kāi)教室的時(shí)間不一致{new Thread(() -> {System.out.println(Thread.currentThread().getName()+"\t 號(hào)同學(xué)離開(kāi)教室");countDownLatch.countDown();}, String.valueOf(i)).start();}countDownLatch.await();System.out.println(Thread.currentThread().getName()+"\t****** 班長(zhǎng)關(guān)門(mén)走人,main線程是班長(zhǎng)");} }CountDownLatch主要有兩個(gè)方法,當(dāng)一個(gè)或多個(gè)線程調(diào)用await方法時(shí),這些線程會(huì)阻塞。
其它線程調(diào)用countDown方法會(huì)將計(jì)數(shù)器減1(調(diào)用countDown方法的線程不會(huì)阻塞),當(dāng)計(jì)數(shù)器的值變?yōu)?時(shí),因await方法阻塞的線程會(huì)被喚醒,繼續(xù)執(zhí)行。
CyclicBarrier
public class CyclicBarrierDemo {private static final int NUMBER = 7;public static void main(String[] args) {//CyclicBarrier(int parties, Runnable barrierAction)CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMBER, () -> {System.out.println("*****集齊7顆龍珠就可以召喚神龍");});//如果沒(méi)有收集到7個(gè),此程序會(huì)一直阻塞,不會(huì)結(jié)束。for (int i = 1; i <= 7; i++) {new Thread(() -> {try {System.out.println(Thread.currentThread().getName() + "\t 星龍珠被收集 ");cyclicBarrier.await();} catch (InterruptedException | BrokenBarrierException e) {// TODO Auto-generated catch blocke.printStackTrace();}}, String.valueOf(i)).start();}} }
字面意思是可循環(huán)(Cyclic)使用的屏障(Barrier)。它要做的事情:讓一組線程到達(dá)一個(gè)屏障(也可以叫同步點(diǎn))時(shí)被阻塞,直到最后一個(gè)線程到達(dá)屏障時(shí),屏障才會(huì)開(kāi)門(mén),所有被屏障攔截的線程才會(huì)繼續(xù)干活。線程進(jìn)入屏障通過(guò)CyclicBarrier的await()方法。
Semaphore
public class SemaphoreDemo {public static void main(String[] args){Semaphore semaphore = new Semaphore(3);//模擬3個(gè)停車(chē)位for (int i = 1; i <=6; i++) //模擬6部汽車(chē){new Thread(() -> {try{semaphore.acquire();System.out.println(Thread.currentThread().getName()+"\t 搶到了車(chē)位");TimeUnit.SECONDS.sleep(new Random().nextInt(5));System.out.println(Thread.currentThread().getName()+"\t------- 離開(kāi)");} catch (InterruptedException e) {e.printStackTrace();}finally {semaphore.release();}}, String.valueOf(i)).start();}} }
在信號(hào)量上我們定義兩種操作:
acquire(獲取) 當(dāng)一個(gè)線程調(diào)用acquire操作時(shí),它要么通過(guò)成功獲取信號(hào)量(信號(hào)量減1),要么一直等下去,直到有線程釋放信號(hào)量,或超時(shí)。
release(釋放)實(shí)際上會(huì)將信號(hào)量的值加1,然后喚醒等待的線程。
信號(hào)量主要用于兩個(gè)目的,一個(gè)是用于多個(gè)共享資源的互斥使用,另一個(gè)用于并發(fā)線程數(shù)的控制。
總結(jié)
- 上一篇: js pug 代码_PUG 系列 | 第
- 下一篇: 解决“不是有效的win32应用程序”