美文网首页
JUC之AQS—Semaphore

JUC之AQS—Semaphore

作者: Toyouy | 来源:发表于2018-06-13 14:48 被阅读0次

    导读:这篇文章介绍的是java并发组件aqs之semaphore(信号量)

    semaphore概念:
    • semaphore可以控制并发访问的线程个数,可以很容易的控制某个资源被同时访问的个数,semaphore维护了当前访问的个数,通过提供同步机制来控制同时访问的个数。同时在数据结构中链表正常是可以保存无限个节点,而semaphore可以实现有限大小的列表。
    semaphore示例图
    semaphore使用场景:
    • 常用于仅能提供有限访问的资源。比如项目中使用数据库,数据库的连接数据比如最大连接只有30,而我们上层应用的并发数会远远超过于此,如果同时对数据库进行操作就有可能出现无法连接数据库而导致异常,这个时候就可以通过semaphore来做并发访问控制。当semaphore把并发控制到1的时候就跟单线程很相似了。
    semaphore中的方法

    下面通过实例来展示下semaphore的使用

    • 1、示列一
    @Slf4j
    public class SemaphoreExample1 {
    
        private final static int threadCount = 20;
    
        public static void main(String[] args) throws Exception {
    
            ExecutorService exec = Executors.newCachedThreadPool();
            final Semaphore semaphore = new Semaphore(3); // 同时允许三个并发访问
    
            for (int i = 0; i < threadCount; i++) {
                final int threadNum = i;
                exec.execute(() -> {
                    try {
                        semaphore.acquire(); // 获取一个许可
                        test(threadNum);
                        semaphore.release(); // 释放一个许可
                    } catch (Exception e) {
                        log.error("except ion", e);
                    }
                });
            }
            exec.shutdown();
        }
    
        //代表业务执行需要一秒
        private static void test(int threadNum) throws Exception {
            log.info("{}", threadNum);
            Thread.sleep(1000);
        }
    }
    

    返回结果:可以看出通过下面的返回结果,一秒只放行了3个。这是因为我们在semaphore初始化的时候定义了同时只允许三个并发访问,而我们控制一个只获取一个许可执行。所以我们得到的结果是每秒有三个线程同时访问

    实例一返回结果
    • 2、实例二:
    @Slf4j
    public class SemaphoreExample2 {
    
        private final static int threadCount = 20;
    
        /**
         * 这里表示当我们并发数是3的时候,而一次性又获取了三个许可,那么同一个时间内相当于是
         * 只能一个test()调用,原因是1次性就拿了三个许可去,这里面同一秒中没有别的许可释放出来了,这时候就和单线程很像了。
         * @param args
         * @throws Exception
         */
        public static void main(String[] args) throws Exception {
    
            ExecutorService exec = Executors.newCachedThreadPool();
            final Semaphore semaphore = new Semaphore(3);
    
            for (int i = 0; i < threadCount; i++) {
                final int threadNum = i;
                exec.execute(() -> {
                    try {
                        semaphore.acquire(3); // 获取三个许可
                        test(threadNum);
                        semaphore.release(3); // 释放三个许可
                    } catch (Exception e) {
                        log.error("exception", e);
                    }
                });
            }
            exec.shutdown();
        }
    
        private static void test(int threadNum) throws Exception {
            log.info("{}", threadNum);
            Thread.sleep(1000);
        }
    }
    

    返回结果:下面的返回结果可以看出我们一秒内只有一次test()方法调用。这里表示当我们并发数是3的时候,而一次性又获取了三个许可,那么同一个时间内相当于是只能一个test()调用,原因是1次性就拿了三个许可去,这里面同一秒中没有别的许可释放出来了,这时候就和单线程很像了。

    实例二返回结果
    • 3、实例三: semaphore.tryAcquire()尝试获取许可
    @Slf4j
    public class SemaphoreExample3 {
    
        private final static int threadCount = 20;
    
        public static void main(String[] args) throws Exception {
    
            ExecutorService exec = Executors.newCachedThreadPool();
    
            final Semaphore semaphore = new Semaphore(3);
    
            for (int i = 0; i < threadCount; i++) {
                final int threadNum = i;
                exec.execute(() -> {
                    try {
                        if (semaphore.tryAcquire()) { // 尝试获取一个许可
                            test(threadNum);
                            semaphore.release(); // 释放一个许可
                        }
                    } catch (Exception e) {
                        log.error("exception", e);
                    }
                });
            }
            exec.shutdown();
        }
    
        private static void test(int threadNum) throws Exception {
            log.info("{}", threadNum);
            Thread.sleep(1000);
        }
    }
    

    返回结果:下面可以看出只有三个线程输出了日志,而其他的线程全部丢弃了。这里解释下为什么,因为我们同时往线程池里放入了20个请求,20个请求在同一个时间内都会去尝试执行test()方法,执行的时候我们的semaphore就会来让每个线程来尝试获取许可,但是同一个时间内我们并发数是3那相当于是只有三个线程获取到了许可,其余的17个线程都没拿到许可直接结束了,因此控制台只输出了三条日志

    实例三返回结果
    • 4、实例四:
    @Slf4j
    public class SemaphoreExample4 {
    
        private final static int threadCount = 20;
    
        public static void main(String[] args) throws Exception {
    
            ExecutorService exec = Executors.newCachedThreadPool();
    
            final Semaphore semaphore = new Semaphore(3);
    
            for (int i = 0; i < threadCount; i++) {
                final int threadNum = i;
                exec.execute(() -> {
                    try {
                        // 这里表示在尝试获取许可的时候尝试等待3秒钟
                        if (semaphore.tryAcquire(3, TimeUnit.SECONDS)) { // 尝试获取一个许可
                            test(threadNum);
                            semaphore.release(); // 释放一个许可
                        }
                    } catch (Exception e) {
                        log.error("exception", e);
                    }
                });
            }
            exec.shutdown();
        }
    
        private static void test(int threadNum) throws Exception {
            log.info("{}", threadNum);
            Thread.sleep(1000);
        }
    }
    

    返回结果:下面返回结果表示三秒内的返回日志,因为semaphore.tryAcquire(3, TimeUnit.SECONDS)表示等待3秒钟,而semaphore控制同时只有三个并发访问,test()方法需要一秒的时间所以只返回了9个值,其余的因为tryAcquire不再等待而丢弃了。

    实例四返回结果

    总结:以上就是aqs中的semaphore的使用介绍,更多的使用可以详细看下semaphore类,semaphore在初始化时还可以定义是否是走公平锁还是非公平锁。semaphore默认是非公平锁
    公平锁的作用就是严格按照线程启动的顺序来执行的,不允许其他线程插队执行的;而非公平锁是允许插队的。

    image.png image.png

    相关文章

      网友评论

          本文标题:JUC之AQS—Semaphore

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