您的位置:首页 > 其它

线程同步工具-Semaphore

2017-06-06 10:36 260 查看
Semaphore(信道)是一个控制访问多个资源的“计数器”

当线程要访问某个资源时,他可以获得Semaphore,如果其内部计数器的值大于0,则允许线程访问并将计数器的值-1.如果内部计数器的值等于0,则表示全部的共享资源已经在被使用.Semaphore会让线程进入休眠.

当线程访问完贡献资源以后,会将Semaphore中计数器的值加1,使资源可以对外提供访问。

public class PrintQueue implements Runnable{
//声明一个对象为Semaphore
private final Semaphore semaphore;

public PrintQueue(Semaphore semaphore) {
this.semaphore = semaphore;
}
//用此类来模拟共享资源 此方法可以模拟打印文档,并接收document对象作为参数
public void printJob(Object document){
try {
//首先需要获取semaphore
semaphore.acquire();
long duration = (long)(Math.random()*10);
System.out.printf("%s: PrintQueue : start print obj in %s seconds\n",Thread.currentThread().getName(),duration);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
//最后必须释放
System.out.printf("%s: PrintQueue end: \n",Thread.currentThread().getName());
semaphore.release();
}
}
@Override
public void run() {
this.printJob(new Object());
}

public static void main(String[] args) {
Semaphore semaphore = new Semaphore(1);
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++) {
threads[i] = new Thread(new PrintQueue(semaphore));
threads[i].start();
}
}
}


输出结果:



上面的方法实现起来可能和Lock的实现方式有些类似,但是与Lock不同的是Semaphore可以控制不同线程同时访问多个资源

如果将

Semaphore semaphore = new Semaphore(1);


这段代码换成如下:

Semaphore semaphore = new Semaphore(3);


则输出结果为:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: