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 }