zoukankan      html  css  js  c++  java
  • Semaphore 并发信号

    package com.thread;
    
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Semaphore;
    import java.util.concurrent.TimeUnit;
    
    /**
     * 并发控制
     **/
    public class SemaphoreTest {
        public static void main(String[] args) {
            test1();
        }
    
        private static void test1() {
            ExecutorService executorService = Executors.newFixedThreadPool(20);
            Semaphore semaphore = new Semaphore(3);//资源最多可被3个线程并发访问
            for (int i = 0; i < 20; i++) {
                executorService.execute(() -> {
                    try {
                        boolean b = semaphore.tryAcquire(1, 300, TimeUnit.MILLISECONDS);//获取许可,300超时,返回false
                        System.out.println("SemaphoreTest.run " + Thread.currentThread().getName() + " b = " + b);
                        Thread.sleep(280);
                        semaphore.release(1);//释放许可
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            executorService.shutdown();//如果不shutdown工程不会结束
        }
    
    
    }

    可以控制并发的数量

  • 相关阅读:
    Django_redis_session
    python_redis操作
    Django_url反向解析
    Django_分页
    Django_cookie与sesstion
    Django 自定义错误页面 403 404...
    Django_设置静态文件、上传文件
    Django设置子路由
    nginx、uwsgi
    CentOS安装MySQL
  • 原文地址:https://www.cnblogs.com/bestzhang/p/11836879.html
Copyright © 2011-2022 走看看