Semaphore可以控制某個資源可被同時訪問的個數,通過 acquire() 獲取一個許可,如果沒有就等待,而 release() 釋放一個許可。比如在Windows下可以設置共享文件的最大客戶端訪問個數。
Semaphore實現的功能就類似廁所有5個坑,假如有10個人要上廁所,那麼同時只能有多少個人去上廁所呢?同時只能有5個人能夠佔用,當5個人中 的任何一個人讓開後,其中等待的另外5個人中又有一個人可以佔用了。另外等待的5個人中可以是隨機獲得優先機會,也可以是按照先來後到的順序獲得機會,這取決於構造Semaphore對象時傳入的參數選項。單個信號量的Semaphore對象可以實現互斥鎖的功能,並且可以是由一個線程獲得了“鎖”,再由另一個線程釋放“鎖”,這可應用於死鎖恢復的一些場合。
Semaphore維護了當前訪問的個數,提供同步機制,控制同時訪問的個數。在數據結構中鏈表可以保存“無限”的節點,用Semaphore可以實現有限大小的鏈表。另外重入鎖 ReentrantLock 也可以實現該功能,但實現上要複雜些。
當訪問個數設置爲1時,其功能等於Lock。
下面我們看一下基本用法:
package javaThread;
import java.util.concurrent.Semaphore;
public class SemaphoreThread {
public static void main(String[] args) {
Semaphore sp = new Semaphore(3);
final SemaphoreData spData = new SemaphoreData(sp);
for (int i = 0; i < 6; i++) {
new Thread(" name " + i) {
public void run() {
spData.opSemaphoreData();
};
}.start();
;
}
}
static class SemaphoreData {
private Semaphore mSp;
public SemaphoreData(Semaphore sp) {
mSp = sp;
}
public void opSemaphoreData() {
try {
mSp.acquire();
System.out.println(" Thread name " + Thread.currentThread().getName());
Thread.sleep(1000);
System.out.println(" Thread name sleep " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
mSp.release();
}
}
}
}
acquire相當於申請鎖,如果進程數沒有達到設置的大小 ,就可以馬上申請到鎖,如果滿了,就等待,
release相當釋放鎖。
Semaphore 更多的是與進程池使用,控制同時訪問的大小 ,
package javaThread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreThreadTest {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
final Semaphore semp = new Semaphore(3);
for (int index = 0; index < 20; index++) {
final int NO = index;
Runnable run = new Runnable() {
public void run() {
try {
semp.acquire();
System.out.println("note : " + NO);
Thread.sleep((long) (Math.random() * 10000));
semp.release();
System.out.println("note : release " +NO );
} catch (InterruptedException e) {
}
}
};
exec.execute(run);
}
exec.shutdown();
}
}
也可以多個Semaphore一起使用實現複雜的功能 ;下面我們就用Semaphore來實現簡單的生產者我消費者模式。
public class SemaphoreProducer {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
Data mData =new Data(4);
for(int i = 0 ;i< 8;i++) {
service.execute(new Producer(mData, " name " +i));
}
service.execute(new Customer(mData, " name 1111111" ));
}
//生產 者和消費者使用隊列
static class Data {
private final int DEFAULT_Size = 10;
private int mCapacity = DEFAULT_Size;
private Semaphore mMutex = new Semaphore(1);
private Semaphore mProduceVisable ,mCustomVisable;
private int mProducesPtr;
private int mCoustomPrt;
private Object [] mData;
public Data() {
}
public Data(int cap) {
mCapacity = cap;
mProduceVisable = new Semaphore(mCapacity);
mCustomVisable = new Semaphore(mCapacity);<pre name="code" class="java"><span style="white-space:pre"> </span> try {
mCustomVisable.acquire(mCapacity);
} catch (InterruptedException e) {
e.printStackTrace();
}
mData = new Object[mCapacity]; mProducesPtr = 0; mCoustomPrt = 0; } public void put(Object object) { mProduceVisable.acquireUninterruptibly();// 是否 mMutex.acquireUninterruptibly(); mData[mProducesPtr] = object; if(++mProducesPtr == mCapacity)
{ mProducesPtr = 0; } mMutex.release(); mCustomVisable.release(); } public Object get() { mCustomVisable.acquireUninterruptibly(); mMutex.acquireUninterruptibly(); Object object = mData[mCoustomPrt]; if(++mCoustomPrt == mCapacity) { mCoustomPrt = 0; } mMutex.release();
mProduceVisable.release(); return object; } } static class Producer extends Thread { private Data mData; private String mName; public Producer(Data data,String name) { mData = data; mName = name; } @Override public void run() { super.run(); while (true) {
Object object = new String("chenqinglin 1"); mData.put(object); System.out.println(" Producer " + mName); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } static class Customer extends
Thread { private Data mData; private String mName; public Customer(Data data,String name) { mData = data; mName = name; } @Override public void run() { super.run(); while (true) { Object object = mData.get(); System.out.println(" Customer " + mName + " object
" + object.toString()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }}
其實看似簡單的Semaphore 也可以完成複雜的功能 .