不同线程池区别:
//newSingleThreadPool:单线程线程池。只有一个线程。线程异常结束的话会再开一个新的替代。保证所有任务按顺序串行
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
//newCachedThreadPool:一个可以无限扩大的线程池,比较适合处理执行时间比较小的任务。
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
//newFixedThreadPool:一个固定大小的线程池,可以用于已知并发压力的情况下,对线程数做限制。
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
//scheduledThreadPool 创建无限制大小的线程池,支持定时和周期性任务执行。
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(10);
feature.get()方法可以拿到异常,避免异常被吞掉。
线程池详情
参数详解
@Test
public void test4() {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 3L,
TimeUnit.SECONDS, new LinkedBlockingDeque<>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 10; i++) {
threadPoolExecutor.execute(() -> {
System.out.println("runnable 实现类");
});
}
}
public static long test() throws ExecutionException, InterruptedException {
List<Future<Object>> results = new ArrayList<>();
//开启多线程
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 15, 3L,
TimeUnit.SECONDS, new LinkedBlockingDeque<>(), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
long l = System.currentTimeMillis();
Future future = threadPoolExecutor.submit(()->{
try {
Thread.sleep(1000);
System.out.println("线程--》1111");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Future future2 = threadPoolExecutor.submit(()->{
try {
Thread.sleep(1000);
System.out.println("线程--》2222");
throw new RuntimeException("exception");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Future future3 = threadPoolExecutor.submit(()->{
try {
Thread.sleep(2000);
System.out.println("线程--》3333");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
future.get();
System.out.println(11111);
future2.get();
System.out.println(22222);
future3.get();
System.out.println(33333);
long l1 = System.currentTimeMillis();
System.out.println(l1-l);
long s = (l1-l)/1000;
return s;
}
数据源连接池一般请求的连接数超过连接池的最大值的时候就会触发拒绝策略,策略一般是阻塞等待设置的时间或者直接抛异常。