线程池(java.util.concurrent.ThreadPoolExecutor)的使用
一、简介
线程池类为 java.util.concurrent.ThreadPoolExecutor,常用构造方法为:
创建 ThreadPoolTask类:
执行结果:
创建任务并提交到线程池中:task@ 1
开始执行任务:task@ 1
创建任务并提交到线程池中:task@ 2
开始执行任务:task@ 2
创建任务并提交到线程池中:task@ 3
创建任务并提交到线程池中:task@ 4
开始执行任务:task@ 3
创建任务并提交到线程池中:task@ 5
开始执行任务:task@ 4
创建任务并提交到线程池中:task@ 6
创建任务并提交到线程池中:task@ 7
创建任务并提交到线程池中:task@ 8
开始执行任务:task@ 5
开始执行任务:task@ 6
创建任务并提交到线程池中:task@ 9
开始执行任务:task@ 7
创建任务并提交到线程池中:task@ 10
开始执行任务:task@ 8
开始执行任务:task@ 9
开始执行任务:task@ 10
@ThreadSafepublic 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(); } }}