什么是Semaphore

发布时间:2021-09-29 16:15:07 作者:iii
来源:亿速云 阅读:162

这篇文章主要介绍“什么是Semaphore”,在日常操作中,相信很多人在什么是Semaphore问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”什么是Semaphore”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

Semaphore(信号量)

注意了,外星人放出一定量的信号(permits),其他外星人接到信号并使用(acquire),使用完后告诉发送人不再使用了(release)。如果信号被用完,只能等待。

用途:多线程运行限流、流量控制、数据库线程池控制、控制顺序执行

提供公平和非公平的两种方式。

class ZeroEvenOdd {
    private int n;
    private Semaphore z = new Semaphore(1);
    private Semaphore e = new Semaphore(0);
    private Semaphore o = new Semaphore(0);
    public ZeroEvenOdd(int n) {
        this.n = n;
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void zero(IntConsumer printNumber) throws InterruptedException {
        for(int i = 0;i<n;i++){
            z.acquire();
            printNumber.accept(0);
            if(i%2 ==0){
                o.release();
            }else{
                e.release();
            }
        }
    }

    public void even(IntConsumer printNumber) throws InterruptedException {
        for(int i = 2;i <= n;i += 2){
            e.acquire();
            printNumber.accept(i);
            z.release();   
        }
    }

    public void odd(IntConsumer printNumber) throws InterruptedException {
        for(int i = 1;i<=n;i+=2){
            o.acquire();
            printNumber.accept(i);
            z.release();  
        }
    }
}

代码中创建了1个信号,有3个对象共享。同一时间只有1个方法执行,默认z有许可证,用完后通知o和e释放,拿到资源后继续执行even或odd方法。

其他方法

Semaphore还提供一些其他方法:

到此,关于“什么是Semaphore”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. Join,CountDownLatch,CyclicBarrier,Semaphore和Exchanger
  2. 42线程4_Semaphore_GIL

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

semaphore

上一篇:怎么解决Ubuntu13.04系统托盘无法显示QQ的问题

下一篇:怎么用国内软件源为Ubuntu的apt-get提速方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》