码迷,mamicode.com
首页 > 其他好文 > 详细

Semaphore信号量

时间:2018-05-03 13:31:09      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:资源   模式   AC   次数   tar   read   mep   tst   窗口   

 

限制并发资源的并发访问数量。 samephore.acquire(); 获取许可  samephore.release(); 释放一个许可。

public class SemaphoreTest implements Runnable {
    Semaphore samephore;
    int id;

    public SemaphoreTest(Semaphore samephore, int id) {
        this.samephore = samephore;
        this.id = id;
    }

    @Override
    public void run() {

        // TODO Auto-generated method stub
        try {
            samephore.acquire();
            Thread.sleep(1000);
            System.out.println("客户编号" + id + "正在办理任务");
            samephore.release();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Semaphore samephore = new Semaphore(10,true);// 限制并发访问次数为10 true为采用公平模式。先进的先遍历
        for (int i = 0; i < 20; i++) {
            new Thread(new SemaphoreTest(samephore, i)).start();;
        }
    }

}

模拟银行10个办理任务的窗口。 samephore.acquire() 如果有10个任务获取许可并没有释放 其他人等待 某一个获取许可正在执行的任务 释放许可才能进入

Semaphore信号量

标签:资源   模式   AC   次数   tar   read   mep   tst   窗口   

原文地址:https://www.cnblogs.com/LQBlog/p/8984770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!