线程同步工具-Semaphore
2017-06-06 10:36
260 查看
Semaphore(信道)是一个控制访问多个资源的“计数器”
当线程要访问某个资源时,他可以获得Semaphore,如果其内部计数器的值大于0,则允许线程访问并将计数器的值-1.如果内部计数器的值等于0,则表示全部的共享资源已经在被使用.Semaphore会让线程进入休眠.
当线程访问完贡献资源以后,会将Semaphore中计数器的值加1,使资源可以对外提供访问。
输出结果:
上面的方法实现起来可能和Lock的实现方式有些类似,但是与Lock不同的是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);
则输出结果为:
相关文章推荐
- 【java并发】线程同步工具Semaphore的使用
- 多线程编程入门(15):线程同步工具之Semaphore(信号量)
- 【java并发】线程同步工具Semaphore的使用
- 【java并发】线程同步工具Semaphore的使用
- 【java并发】线程同步工具Exchanger的使用
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 基元线程同步——内核模式构造(WaitHandle,EventWaitHandle,AutoResetEvent,ManualResetEvent,Semaphore,Mutex)
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- [C#学习笔记之多线程2]多线程同步与并发访问共享资源工具—Lock、Monitor、Mutex、Semaphore .
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 多线程之八 经典线程同步 信号量Semaphore
- 线程同步----信号量(Semaphore)
- 线程同步----信号量(Semaphore)
- 线程同步:旗语(Semaphore)
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 线程同步工具之CountDownLatch
- 秒杀多线程第八篇 经典线程同步 信号量Semaphore
- 进程/线程同步——Critical Section,Mutex,Semaphore,Event区别
- 进程/线程同步——Critical Section,Mutex,Semaphore,Event区别
- 【5】Java并发编程:线程同步工具之CountDownLatch类