常用的輔助類
阿新 • • 發佈:2022-04-18
CountDownLatch
// 減法計數器 public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { // 總數是6 必須要執行任務的時候,再使用! CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 0; i < 6; 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 CyclicBarrierDemo { public static void main(String[] args) { /** * 集齊7顆龍珠召喚神龍 */ // 召喚龍珠的執行緒 CyclicBarrier cyclicBarrier = new CyclicBarrier(7, () -> { System.out.println("召喚神龍成功~"); }); for (int i = 0; i < 7; i++) { final int temp = i; // lambda能操作到i麼 new Thread(()->{ System.out.println(Thread.currentThread().getName() + "收集" + temp + "個龍珠"); try { cyclicBarrier.await();// 等待 } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } } }
Semaphore
public class SemaphoreDemo { public static void main(String[] args) { // 執行緒數量: 停車位! 限流! Semaphore semaphore = new Semaphore(3); for (int i = 0; i < 6; i++) { new Thread(() -> { // acquire() 得到 try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "搶到車位"); TimeUnit.SECONDS.sleep(2); System.out.println(Thread.currentThread().getName() + "離開車位"); } catch (InterruptedException e) { e.printStackTrace(); } finally { // release() 釋放 semaphore.release(); } }, String.valueOf(i)).start(); } } }