Semaphore,是用于控制一組線程訪問資源。舉個例子,老師上課,同學需要上廁所,老師準備了3個令牌,拿到令牌的同學就可以去上廁所,上完廁所的同學需要歸還令牌。這樣就最多同時只有3名同學上廁所。這就是Semaphore的應用場景。
Semaphore的構(gòu)造函數(shù)可初始化令牌數(shù)量、是否公平鎖。如果是公平鎖,先申請令牌的可以先獲取。
acquire() 和release()分別是獲取和釋放令牌,acquire(int) 和release(int) 分別是獲取和釋放多個令牌。
例子實現(xiàn)如下:
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* Created by ganliang on 15/2/26.
*/
public class SemaphoreTest {
private static Semaphore semaphore = new Semaphore(3,true);
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i=0;i<10;i++){
executorService.submit(new Student("學生"+i));
}
executorService.shutdown();
}
static class Student implements Runnable{
private String name;
public Student(String name){
this.name = name;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(name+"拿到令牌,上廁所");
TimeUnit.SECONDS.sleep(new Random().nextInt(10));
} catch (InterruptedException e) {
e.printStackTrace();
}
semaphore.release();
System.out.println(name+"歸還令牌,上課");
}
}
}