Java 利用线程池创建并发线程

2014-11-24 09:22:29 · 作者: · 浏览: 1

import java.util.concurrent.ArrayBlockingQueue;


import java.util.concurrent.ThreadPoolExecutor;


import java.util.concurrent.TimeUnit;



public class ThreadPoolExecutorUtil {



// 池中所保存的线程数,包括空闲线程


private static final int corePoolSize = 10;


// 池中允许的最大线程数


private static final int maximumPoolSize = 100;


// 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间(目前设为1800秒即30分钟)


private static final int keepAliveTime = 1800;


// 执行前用于保持任务的队列


private static final int blockingQueueSize = 10;


// 参数的时间单位


private static final TimeUnit unit = TimeUnit.SECONDS;



private static ThreadPoolExecutor threadPool = null;



/**


* 获取线程池的单例


* @return


*/


public static ThreadPoolExecutor getPoolInstance() {


if (threadPool == null) {


synchronized (ThreadPoolExecutor.class) {


// 实例化线程池


threadPool = new ThreadPoolExecutor(corePoolSize,


maximumPoolSize, keepAliveTime, unit,


new ArrayBlockingQueue(blockingQueueSize),


new ThreadPoolExecutor.DiscardOldestPolicy());


}


}


// 返程线程池的实例化对象


return threadPool;


}



public static void main(String[] args) {


for (int i = 0; i < 10; i++) {


// 实例化线程池


ThreadPoolExecutor threadPool = ThreadPoolExecutorUtil


.getPoolInstance();


// 触发并行线程的运行


threadPool.execute(new SingleThread(i+""));


}


}



}



class SingleThread implements Runnable {



private String name = null;



public SingleThread(String name) {


this.name = name;


}



public void run() {


System.out.println("parallel run..." + name);


}



}