CountDownLatch、CyclicBarrier、Semaphore
阿新 • • 發佈:2022-05-11
CountDownLatch的使用
/* 減法計數器 */ public class Test1 { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(10);//一共減10次 for (int i = 1; i < 11; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName() + " Go Out"); countDownLatch.countDown();//每次減一 }, String.valueOf(i)).start(); } countDownLatch.await();//等待計數器歸零 再繼續向下執行 System.out.println("Close Door"); } }
CyclicBarrier的使用
/* 加法計數器 */ public class Test { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(7, ()->{ System.out.println("集齊了龍珠"); }); for (int i = 1; i < 8; i++) { int temp = i; new Thread(/*()->{ System.out.println(Thread.currentThread().getName()+"收集第"+ temp +"顆龍珠"); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }*/ new Runnable() { @Override public void run() { System.out.println(Thread.currentThread().getName()+"收集第"+ temp +"顆龍珠"); try { cyclicBarrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }, String.valueOf(temp)).start(); } } }
Semaphore的使用
/* 執行緒數量限制 */ public class Test3 { public static void main(String[] args) { //執行緒數量 限流用 Semaphore semaphore = new Semaphore(3); for (int i = 1; i < 7; i++) { new Thread(()->{ try { semaphore.acquire();//搶到車位 System.out.println(Thread.currentThread().getName()+"搶到了車位"); TimeUnit.SECONDS.sleep(1); System.out.println(Thread.currentThread().getName()+"離開了車位"); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release();//離開車位 } }, String.valueOf(i)).start(); } } }