使用信号量来 限制无边界池子与队列

  使用信号量来 限制无边界池子与队列

 

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 (RejectedExecutionException e) {
                 semaphore.release();
           }
     }
}

 

posted @ 2015-01-22 16:45  mjorcen  阅读(225)  评论(0编辑  收藏  举报