JUC之輔助類Semaphore
阿新 • • 發佈:2022-04-10
模擬一個樣例,6輛汽車搶佔3個停車位
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()+"搶到了車位"); //設定停車時間0~1500ms TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1500)); System.out.println(Thread.currentThread().getName()+"----離開了車位"); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release(); } },String.valueOf(i)).start(); } } }