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

    可以控制并发的数量

  • 相关阅读:
    关于学习方法
    ES6的异步操作
    Promise对象的基本用法
    Generator函数(三)
    Generator函数(二)
    Generator函数(一)
    ES6 Set结构和Map结构(上)
    mybatis02--增删改查
    myBatis01
    监听器
  • 原文地址:https://www.cnblogs.com/bestzhang/p/11836879.html
Copyright © 2011-2022 走看看