zoukankan      html  css  js  c++  java
  • 使用信号量semaphore实现一个无界线程池

    Semaphore 用法 在调用accquire之后到release之间,别的线程会阻塞,当然前提是信用量已经没有可用的了。

     1 package com.citi.test.mutiplethread.demo08;
     2 
     3 import java.util.concurrent.Executor;
     4 import java.util.concurrent.Semaphore;
     5 
     6 public class BoundedExecutor {
     7     private final Executor exec;
     8     private final Semaphore semaphore;
     9     public BoundedExecutor(Executor exec,int bound) {
    10         this.exec=exec;
    11         this.semaphore=new Semaphore(bound);
    12     } 
    13     public void submitTask(final Runnable runnable) throws InterruptedException{
    14         //获取一个许可 在acquire之后如果信号量已经没有了,那么下个线程再进来会等待,直到有线程调用release方法
    15         semaphore.acquire();
    16         try {
    17             exec.execute(new Runnable() {
    18                 @Override
    19                 public void run() {
    20                     try {
    21                         runnable.run();
    22                     }finally{
    23                         semaphore.release();
    24                     }
    25                 }
    26             });
    27         } catch (Exception e) {
    28             semaphore.release();
    29         }
    30     }
    31 }
  • 相关阅读:
    vue 之 vuex
    vue中this.$router.push() 传参
    ES6新特性
    css优先级
    创建第一个vue工程
    对Vue.js的认知
    前端的认知与见解
    Web前端常见问题
    数据库如何进行索引优化
    Python FAQ
  • 原文地址:https://www.cnblogs.com/liumy/p/11861101.html
Copyright © 2011-2022 走看看