线程同步工具-Semaphore

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);

则输出结果为:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值