Semaphore介绍
Semaphore是java并发编程中出现的一个工具,其具体的作用是用来控制java中对资源的使用。比如我们常用的数据库连接,加入我们希望能够限制同一时间持有数据库连接的数量,我们就可以使用到Semaphore这个工具。
Semaphore介绍
信号量的特性如下:信号量是一个非负整数(车位数),所有通过它的线程(车辆)都会将该整数减一(通过它当然是为了使用资源),当该整数值为零时,所有试图通过它的线程都将处于等待状态。在信号量上我们定义两种操作: Wait(等待) 和 Release(释放)。 当一个线程调用Wait(等待)操作时,它要么通过然后将信号量减一,要么一直等下去,直到信号量大于一或超时。Release(释放)实际上是在信号量上执行加操作,对应于车辆离开停车场,该操作之所以叫做“释放”是因为加操作实际上是释放了由信号量守护的资源。在这个停车场系统中,车位是公共资源,每辆车好比一个线程,看门人起的就是信号量的作用。
Semaphore主要使用有两个场景
1、与java无界线程池一起使用,来限制线程的到达率
1.1 BounderExecutor.java
public class BounderExecutor {
private final Executor exec;
private final Semaphore semaphore;
public BounderExecutor(Executor exec,int bound){
this.exec = exec;
this.semaphore = new Semaphore(bound);
}
public void submitTask(final Runnable command)
throws InterruptedException{
semaphore.acquire();
try{
exec.execute(new Runnable() {
public void run() {
try{
command.run();
}finally{
semaphore.release();
}
}
});
}catch(RejectedExecutionException e){
semaphore.release();
}
}
}
1.2 SemaphoreDemo.java
public static void main(String[] args) {
BounderExecutor exec = new BounderExecutor(Executors.newCachedThreadPool(), 2);
Runnable run1 = new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("r1");
}
};
Runnable run2 = new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("r2");
}
};
Runnable run3 = new Runnable() {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("r3");
}
};
Runnable run4 = new Runnable() {
public void run() {
System.out.println("r4");
}
};
Runnable run5 = new Runnable() {
public void run() {
System.out.println("r5");
}
};
try {
exec.submitTask(run1);
exec.submitTask(run2);
exec.submitTask(run3);
exec.submitTask(run4);
exec.submitTask(run5);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
1.3 输出结果
r1
r2
r4
r5
r3
无界队列:不能限制队列大小和任务到达率
如果使用Executors.newCachedThreadPool()获得的Exector就是无界的。因为对于线程池来说并不是不断地开辟线程就是最好的,应该适应一定的情况,选择一个适当的大小。对于许多有界队列来说是很好做到的。但是对于那些无界队列,则需要使用到Semaphore。
正如代码中所示的一样,在BounderExecutor.java中,通过构造方法,我们传入Exector和Semaphore的大小。通过构造方法初始化。可以认为Semaphore的大小就是同一时间可以使用资源的数量,也就是开头我们认为车库。acquire方法就是获取一个进入车库的钥匙。而release方法就是讲钥匙还给管理员,由管理员给下一个等待进入车库的车辆。如果没有了车库钥匙,所有的汽车必须等待着。
2、对资源的访问控制
public class MutexPrint
{
/**
* 定义初始值为1的信号量
*/
private final Semaphore semaphore = new Semaphore(1);
/**
* 模拟打印操作
* @param str
* @throws InterruptedException
*/
public void print(String str) throws InterruptedException
{
//请求许可
semaphore.acquire();
System.out.println(Thread.currentThread().getName()+" enter ...");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() + "正在打印 ..." + str);
System.out.println(Thread.currentThread().getName()+" out ...");
//释放许可
semaphore.release();
}
public static void main(String[] args)
{
final MutexPrint print = new MutexPrint();
/**
* 开启10个线程,抢占打印机
*/
for (int i = 0; i < 10; i++)
{
new Thread()
{
public void run()
{
try
{
print.print("helloworld");
} catch (InterruptedException e)
{
e.printStackTrace();
}
};
}.start();
}
}
}
输出结果位:
Thread-1 enter ...
Thread-1正在打印 ...helloworld
Thread-1 out ...
Thread-2 enter ...
Thread-2正在打印 ...helloworld
Thread-2 out ...
Thread-0 enter ...
Thread-0正在打印 ...helloworld
Thread-0 out ...
Thread-3 enter ...
Thread-3正在打印 ...helloworld
Thread-3 out ...