美文网首页
java.util.concurrent.Semaphore实战

java.util.concurrent.Semaphore实战

作者: 奋斗的韭菜汪 | 来源:发表于2020-06-23 21:29 被阅读0次

信号灯[ˈseməfɔːr]

public class SemaphoreDemo {

    public static void main(String[] args) {
        //令牌桶,有5个令牌
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 10; i++){
            new DoAnything(i, semaphore).start();
        }
    }

    static class DoAnything extends Thread{
        private int num;
        private Semaphore semaphore;

        public DoAnything(int num,  Semaphore semaphore){
            this.num = num;
            this.semaphore = semaphore;
        }

        //限制流量
        @Override
        public void run(){
            try {
                //获取令牌(从五个令牌中获取,获取不到令牌则阻塞)
                semaphore.acquire();
                System.out.println("第" + num + "线程进入");
                Thread.sleep(2000);
                //释放令牌(令牌释放后,semaphore.acquire会重新获得令牌)
                semaphore.release();
                System.out.println("第" + num + "线程释放");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

运行结果

第0线程进入
第2线程进入
第1线程进入
第3线程进入
第4线程进入
第0线程释放
第3线程释放
第8线程进入
第2线程释放
第4线程释放
第1线程释放
第9线程进入
第6线程进入
第5线程进入
第7线程进入
第9线程释放
第7线程释放
第6线程释放
第5线程释放
第8线程释放

Process finished with exit code 0

相关文章

网友评论

      本文标题:java.util.concurrent.Semaphore实战

      本文链接:https://www.haomeiwen.com/subject/elskfktx.html