之前和大家分享過CountDownLatch和CyclicBarrier
======相關鏈接=====
想了解CountDownLatch的同學請點擊埃索達傳送門
想了解CyclicBarrier的同學請點擊鐵爐堡傳送門
下面說個場景,例如我有一個資源,只想讓2個線程訪問,當一個線程釋放了資源,其他線程纔可以有機會訪問這個資源,這樣的場景用之前的線程同步工具好像都不太好使,所以這裏給大家介紹一個新的工具Semaphore,廢話不說直接上代碼
public class SemaphoreDemo {
public static void main(String[] args) {
//構造對象,第一個參數爲可訪問資源的線程數,第二個參數爲是否爲公平鎖,不傳默認爲公平鎖
Semaphore semaphore = new Semaphore(2,false);
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" start");
try {
semaphore.acquire();//佔用資源
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" end");
semaphore.release();//釋放資源
}
};
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(runnable);
thread.start();
try {
thread.sleep(5);//休眠5毫秒,目的讓他們有序進入等待隊列
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
代碼很好理解,首先構造這個類,參數說明看註釋,之後鎖定資源,釋放資源
大家可以拷代碼試一試,這個信號量semaphore不難理解,就不多說了