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工程不会结束
        }
    
    
    }

    可以控制并发的数量

  • 相关阅读:
    计算欧拉函数值
    矩阵快速幂
    约瑟夫环数学公式
    整型输出输入优化
    计算机设计第三章
    计算机设计第二章
    计算机设计
    阿里巴巴秋招2017客户端附加题
    程序设计基本概念
    c++面试题
  • 原文地址:https://www.cnblogs.com/bestzhang/p/11836879.html
Copyright © 2011-2022 走看看