public class BoundedExecutor {
private final Executor exec;
private final Semaphore semaphore;
public BoundedExecutor(Executor exec,int bound){
this.exec = exec;
semaphore = new Semaphore(bound);
}
public void sumbitTask(final Runnable command) throws InterruptedException{
long time_here = System.currentTimeMillis();
semaphore.acquire();
System.out.println("获取锁所耗时间:" +(System.currentTimeMillis()-time_here));
try{
exec.execute(new Runnable(){
public void run(){
try{
command.run();
}finally{
semaphore.release();
}
}
});
}catch(RejectedExecutionException e){
semaphore.release();
}
}
public static void main(String[] args) throws InterruptedException{
int N_THREADS = 3;
int CAPACITY = 3;
ThreadPoolExecutor executor = new ThreadPoolExecutor(N_THREADS,N_THREADS,0L,TimeUnit.MICROSECONDS,new LinkedBlockingQueue<Runnable>(CAPACITY));
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
System.out.println("main thread:["+Thread.currentThread().getName()+"]");
BoundedExecutor b = new BoundedExecutor(executor,7);
for(int i=0;i<10;i++){
b.sumbitTask(new Runnable(){
public void run(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("正在运行任务的线程:thread["+Thread.currentThread().getName()+"]");
}
});
}
}
}
“`
运行结果:
main thread:[main]
获取锁所耗时间:0
获取锁所耗时间:0
获取锁所耗时间:0
获取锁所耗时间:0
获取锁所耗时间:0
获取锁所耗时间:0
获取锁所耗时间:0
正在运行任务的线程:thread[pool-1-thread-3]
正在运行任务的线程:thread[pool-1-thread-1]
正在运行任务的线程:thread[pool-1-thread-2]
正在运行任务的线程:thread[main]
获取锁所耗时间:0
获取锁所耗时间:0
获取锁所耗时间:0
正在运行任务的线程:thread[pool-1-thread-2]
正在运行任务的线程:thread[pool-1-thread-3]
正在运行任务的线程:thread[pool-1-thread-1]
正在运行任务的线程:thread[pool-1-thread-3]
正在运行任务的线程:thread[pool-1-thread-1]
正在运行任务的线程:thread[pool-1-thread-2]