如果不了解线程池的各个参数的含义,可以查看此文章线程池的优点、以及各个参数的意义、使用示例
两个构造方法
一个多了一个线程工厂的参数,能够对参数名等进行设置
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
ExecutorService executorService2 = Executors.newFixedThreadPool(3, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("我是newFixedThreadPool,你来打我呀");
return thread;
}
});
}
构造理解
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
- FixedThreadPool用于创建线程数固定的线程池,他的corePoolSize=maximumPoolSize=初始化长度
- 当线程数>corePoolSize,等待时间默认是0,意味着多余的线程会立马跑出异常终止
- 使用LinkedBlockingQueue有界阻塞队列,默认容量是Integer.MAX_VALUE
适用场景
适用于负载比较中的服务器,及内存资源有限
使用demo
public class Test {
static class Customer extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--开始执行");
try {
//模拟任务执行4s
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "--执行完成");
}
}
static class Home implements Callable {
int start;
int end;
public Home(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = start; i <=end; i++) {
sum+=i;
}
return sum;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
ExecutorService executorService2 = Executors.newFixedThreadPool(3, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setName("我是newFixedThreadPool,你来打我呀");
return thread;
}
});
//执行普通没有返回值的任务
executorService.execute(new Customer());
//执行有返回值的任务
Future submit = executorService.submit(new Home(1, 10));
System.out.println("get()方法会阻塞,直到拿到结果"+submit.get());
//执行普通没有返回值的任务
executorService2.execute(new Customer());
//执行有返回值的任务
Future submit2 = executorService2.submit(new Home(1,10));
System.out.println("get()方法会阻塞,直到拿到结果"+submit2.get());
}
}
结果:
pool-1-thread-1--开始执行
get()方法会阻塞,直到拿到结果55
我是newFixedThreadPool,你来打我呀--开始执行
get()方法会阻塞,直到拿到结果55
pool-1-thread-1--执行完成
我是newFixedThreadPool,你来打我呀--执行完成