java 线程池
常用线程池
1. ThreadPoolExecutor
//构造函数
public ThreadPoolExecutor(int corePoolSize,int maximumPoolSize,long keepAliveTime,TimeUnit unit,
BlockingQueue<Runnable> workQueue,ThreadFactory threadFactory,RejectedExecutionHandler handler);
- corePoolSize:核心池的大小,这个参数跟后面讲述的线程池的实现原理有非常大的关系。在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务,除非调用了prestartAllCoreThreads()或者prestartCoreThread()方法,从这2个方法的名字就可以看出,是预创建线程的意思,即在没有任务到来之前就创建corePoolSize个线程或者一个线程。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
- maximumPoolSize:线程池最大线程数,这个参数也是一个非常重要的参数,它表示在线程池中最多能创建多少个线程;
- keepAliveTime:表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize,即当线程池中的线程数大于corePoolSize时,如果一个线程空闲的时间达到keepAliveTime,则会终止,直到线程池中的线程数不超过corePoolSize。但是如果调用了allowCoreThreadTimeOut(boolean)方法,在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0;
- unit:参数keepAliveTime的时间单位。
- workQueue:一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响
- handler:表示当拒绝处理任务时的策略
2. ScheduledThreadPoolExecutor
创建线程池的方法
通常使用Executors工厂类实现线程池
* newFixedThreadPool();
//斐波那契数列,模拟线程处理任务的时延
public static int fbc(int n){
if(n == 0) return 0;
if(n == 1) return 1;
return fbc(n-1) + fbc(n-2);
}
//创建线程数目确定的线程池,corePoolSize = maximumPoolSize , workQuene是LinkedBlockingQuene无界限
public static void testFixedThreadPool() throws InterruptedException, ExecutionException{
ExecutorService executorService = Executors.newFixedThreadPool(3);
for(int i=0; i<9; i++){
Future<Integer> future = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
System.out.println("执行线程:"+Thread.currentThread().getName());
return fbc(0);
}
});
System.out.println("第"+i+"次结果:"+" "+future.get());
}
}
- newCachedThreadPool();
//创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
public static void testCachedThreadPool() throws InterruptedException, ExecutionException{
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i=0; i<9; i++){
Future<Integer> future = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
System.out.println("执行线程:"+Thread.currentThread().getName());
return fbc(0);
}
});
//System.out.println("第"+i+"次结果:"+" "+future.get());
}
}
- newScheduledThreadPool();
//创建周期执行的线程池,第一个参数是线程任务,第二个参数延迟n,第三个参数是每隔m执行一次,第四个是时间单位。
public static void testScheduledThreadPool(){
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
executorService.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("第1次:"+fbc(20) + "--->"+Thread.currentThread().getName());
}
},1,3,TimeUnit.SECONDS);
executorService.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("第2次:"+fbc(20) + "--->"+Thread.currentThread().getName());
}
},1,3,TimeUnit.SECONDS);
}
- newSingleExecutor();
//创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
public static void testSingleExecutor() throws InterruptedException, ExecutionException{
ExecutorService executorService = Executors.newSingleThreadExecutor();
for(int i=0; i<9; i++){
Future<Integer> future = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
// TODO Auto-generated method stub
System.out.println("执行线程:"+Thread.currentThread().getName());
return fbc(20);
}
});
System.out.println("第"+i+"次结果:"+" "+future.get());
}
}
配置线程池大小
一般需要根据任务的类型来配置线程池大小:
如果是CPU密集型任务,就需要尽量压榨CPU,参考值可以设为 NCPU+1。
如果是IO密集型任务,参考值可以设置为2*NCPU,很多线程在等IO资源没有工作。