深入理解JUC:第六章:Semaphore信號(hào)燈
理論:
Semaphore 是 synchronized 的加強(qiáng)版,作用是控制線程的并發(fā)數(shù)量
多個(gè)線程搶多個(gè)資源,下面案例是有六臺(tái)車(chē)搶三個(gè)停車(chē)位
使用Semaphore的代碼:
public class Demo {
public static void main(String[] args) throws Exception{
//模擬三個(gè)停車(chē)位
Semaphore semaphore = new Semaphore(3);
//模擬六臺(tái)車(chē)
for (int i = 1; i <= 6; i++) {
new Thread(()->{
try {
semaphore.acquire();//減一
//semaphore.release();//加一
//semaphore.release(2);//加二
System.out.println(Thread.currentThread().getName()+"\t 搶到車(chē)位");
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName()+"\t 停車(chē)2秒后離開(kāi)車(chē)位");
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
},String.valueOf(i)).start();
}
}
}
控制臺(tái):