java.util.concurrent包探秘(一)之Executors
package com.gw.concurrent;import java.io.IOException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;/** *@author zcc *@date 2013-7-24 *@description *@version 1.0.0 */public class TestNewFixedThreadPool{public static void main(String[] args) throws IOException,InterruptedException{ExecutorService service = Executors.newFixedThreadPool(2);for(int i = 0; i < 4; i++){Runnable run = new Runnable() {public void run(){for(int j = 0; j < 10; j++){System.out.println(j);}}};service.execute(run);}service.shutdown();service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);System.out.println("all thread complete");}}
???? newFixedThreadPool生成一个固定的线程池,顾名思义,线程池的线程是不会释放的,即使它是Idle。这就会产生性能问题,比如如果线程池的大小为200,当全部使用完毕后,所有的线程会继续留在池中,相应的内存和线程切换(while(true)+sleep循环)都会增加。如果要避免这个问题,就必须直接使用ThreadPoolExecutor()来构造。可以像Tomcat的线程池一样设置“最大线程数”、“最小线程数”和“空闲线程keepAlive的时间”。
???
public class TestThreadPoolExecutor {public static void main(String[] args) {BlockingQueue<Runnable> queue = new LinkedBlockingQueue<Runnable>();ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 6, 1, TimeUnit.DAYS, queue);for (int i = 0; i < 20; i++) {final int index = i;executor.execute(new Runnable() {public void run() {try {Thread.sleep(4000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(String.format("thread %d finished", index));}});}executor.shutdown();}}
?
?