Semaphore信号量

限制并发资源的并发访问数量。 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个任务获取许可并没有释放 其他人等待 某一个获取许可正在执行的任务 释放许可才能进入

猜你喜欢

转载自www.cnblogs.com/LQBlog/p/8984770.html