直接上代码,参考自http://www.cnblogs.com/answer1991/archive/2012/04/22/2464524.html
import java.awt.dnd.Autoscroll;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadPoolUtil {
//核心线程数
private static final int CORE_POOL_SIZE = 5;
//最大线程数
private static final int MAX_POOL_SIZE = 100;
//线程存活时间
private static final int KEEP_ALIVE_TIME = 10000;
//线程存放队列
private static BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(
10);
private static ThreadPoolExecutor mExecutor;
private static ThreadFactory threadFactory = new ThreadFactory() {
private final AtomicInteger integer = new AtomicInteger();
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "my thread :" + integer);
}
};
static {
mExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE,
KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue, threadFactory);
}
private ThreadPoolUtil() {
}
public static void execute(Runnable runnable) {
mExecutor.execute(runnable);
}
}
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
ThreadPoolUtil.execute(new MyRunnable());
}
}
class MyRunnable implements Runnable
{
@Override
public void run() {
System.out.println("myRynnable runs");
}
}