使用Semaphore控制任务提交速率

public class BoundedExecutor{
    
    
  private final Executor exec;
  private final Semaphore semaphore;

  public BoundedExecutor(Executor exec,int bound){
    
    
    this.exec = exec;
    this.semaphore = new Semaphore(bound);
  }

  public void submitTask(final Runnable command) throws InterruptedException{
    
    
    semaphore.acquire();
    try{
    
    
      exec.execute(
        new Runnable(){
    
    
          public void run(){
    
    
            try{
    
    
              command.run();
            }finally{
    
    
              semaphore.release();
            }
          }
        }
      );
    }catch(RejectExecutionException e){
    
    
       semaphore.release();
    }
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_37632716/article/details/118736726