如果不了解线程池的各个参数的含义,可以查看此文章线程池的优点、以及各个参数的意义、使用示例
两个构造方法
一个多了一个线程工厂的参数,能够对参数名等进行设置
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService1 = Executors.newCachedThreadPool ();
ExecutorService executorService2 = Executors.newCachedThreadPool( new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("我是newCachedThreadPool ,你来打我呀");
return thread;
}
});
}
}
构造理解
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
- corePoolSize=0;maximumPoolSize=Integer.MAX_VALUE,最大会创建Integer.MAX_VALUE线程执行任务
- 等待时间默认是60秒,意味着空闲线程等待60无任务就会终止
- 使用CachedThreadPool无界阻塞队列,会不断创建线程
适用场景
适用于执行很多短期异步任务的小程序,或者负载较轻的服务器
使用demo
public class Test {
static class Customer extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--开始执行");
try {
//模拟任务执行4s
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--执行完成");
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService1 = Executors.newCachedThreadPool ();
ExecutorService executorService2 = Executors.newCachedThreadPool( new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("我是newFixedThreadPool,你来打我呀");
return thread;
}
});
//执行普通没有返回值的任务,这两个任务会按照顺序执行
for (int i = 0; i < 10; i++) {
executorService1.execute(new Customer());
}
executorService1.execute(new Customer());
//执行有返回值的任务
Future submit = executorService1.submit(new Home(1, 10));
System.out.println("get()方法会阻塞,直到拿到结果"+submit.get());
}
}
结果:
pool-1-thread-1--开始执行
get()方法会阻塞,直到拿到结果55
我是newFixedThreadPool,你来打我呀--开始执行
get()方法会阻塞,直到拿到结果55
pool-1-thread-1--执行完成
我是newFixedThreadPool,你来打我呀--执行完成