在java开发中经常使用线程池去提升程序的性能,进行现场复用,降低系统资源消耗、提升系统响应速度。如并发请求的数量非常大,每个请求的实际处理耗时又非常短,就会频繁的创建和销毁线程,降低系统的性能。
java中的线程池:Executor接口》ExecutorService接口》ThreadPoolExecutor实现类
ThreadPoolExecutor构造方法:
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ? null : AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
构造器中各个参数的说明如下:
corePoolSize:核心线程数。默认情况下核心线程会一直保持,即使这些线程是空闲的也是会一直存在的,可以理解为线程池中的常驻线程。
从JDK1.6开始,可以使用ThreadPoolExecutor#allowCoreThreadTimeOut(true)方法改变此策略。即当设置为true 时,线程池中的核心线程在空闲时间达到keepAliveTime时也会销毁。
maximumPoolSize:最大线程数,该线程池最大允许创建的线程总数。
keepAliveTime:所允许的非核心线程空闲时间。当线程池中的实际线程数量大于corePoolSize时,如果没有新的任务需要执行,核心线程之外的线程不会立即销毁,而是会等待任务,当等待的时间超过了keepAliveTime时会被销毁。
unit:上述等待时间的单位,比如毫秒、秒。
workQueue:等待队列。提交任务时,如果此时线程池中的线程数已经大于等于corePoolSize了,则会把该任务封装成一个Worker对象放入等待队列中。
threadFactory:线程工厂。用来创建具体的线程对象的一个工厂类。如果没有指定默认会使用Executors.defaultThreadFactory()作为线程工厂。
handler:拒绝策略。当线程池中的线程数达到了最大限制,并且等待队列也已经满了的情况下的处理策略。线程池已经提供了如下4种策略。
- AbortPolicy:直接抛出运行时RejectedExecutionException异常,这是默认策略;
- CallerRunsPolicy:由调用者自身的线程来执行该任务,该任务最终会被执行;
- DiscardPolicy:直接丢弃任务,不做任何处理,不报异常;
- DiscardOldestPolicy:丢弃等待队列中队头的任务(最老的任务),并尝试执行当前任务;如果失败,重复此过程。
实例:
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20,
60L, TimeUnit.SECONDS, new ArrayBlockingQueue(10000));
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println("run task...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("run task done!");
}
});
System.out.println("main thread running");
threadPoolExecutor.shutdown();
}
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5,
60L, TimeUnit.SECONDS,
new ArrayBlockingQueue(3), new NamedThreadFactory("my-task-pool"),
new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 0; i < 12; i++) {
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " run task...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
System.out.println("main thread running");
threadPoolExecutor.shutdown();
}
public class NamedThreadFactory implements ThreadFactory {
private String namePrefix;
private AtomicInteger threadNumber = new AtomicInteger(1);
private SecurityManager s = System.getSecurityManager();
private ThreadGroup group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
public NamedThreadFactory(String namePrefix) {
this.namePrefix = namePrefix;
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r, namePrefix + "-thread-" + threadNumber.getAndIncrement(), 0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
本例中提交了12个任务,由于最大线程数是5,且队列大小为3。因此在极限条件下只能处理8个任务。