Semaphore,是用于控制一组线程访问资源。举个例子,老师上课,同学需要上厕所,老师准备了3个令牌,拿到令牌的同学就可以去上厕所,上完厕所的同学需要归还令牌。这样就最多同时只有3名同学上厕所。这就是Semaphore的应用场景。
Semaphore的构造函数可初始化令牌数量、是否公平锁。如果是公平锁,先申请令牌的可以先获取。
acquire() 和release()分别是获取和释放令牌,acquire(int) 和release(int) 分别是获取和释放多个令牌。
例子实现如下:
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+"归还令牌,上课");
}
}
}