常用的线程池调用
1.一线程池N任务
private static ExecutorService executorService1 = Executors.newFixedThreadPool(5);
2.一池一线程
private static ExecutorService executorService2 = Executors.newSingleThreadExecutor();
3.线程池根据需求创建线程,可扩容,遇强则强
private static ExecutorService executorService3 = Executors.newCachedThreadPool();
具体的调用:只写一个关于newFixedThreadPool(int nThreads) nThread是存活5个线程
for (int i = 0; i < 10; i++) {
executorService1.execute(()->{
System.out.println(Thread.currentThread().getName()+"办理业务");
});
}
executorService1.shutdown();
但实际上线程池不允许使用Executors去创建,而是ThreadPoolExecutor的方式,这样的处理方式,可以避免资源耗尽的风险
为什么呢
FixedThreadPool和SingleThreadPool:
允许的请求队列长度为Interger.MAX_VALUE,可能会堆积大量的请求,从而导致OOM
CachedThreadPool和ScheduledThreadPool:
允许创建的线程数量为Integer.MAX_VALUE.肯会创建大量线程,从而导致OOM
现在我们使用自定义线程池,
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler)
下面我们对此依次解释:
corePoolSize是代表着核心线程数
maximumPoolSize代表最大线程数
long keepAliveTime 存活时间。如果当前线程数量大于核心数量,会释放空闲的线程,只要空闲的线程超时,释放
TimeUnit unit 时间单位
BlockingQueue<Runnable> workQueue,阻塞队列,如果任务有很多,就会将目前多的任务放入队列,只要有线程空闲,就会在队列里取新的任务放进去,继续执行
ThreadFactory threadFactory,线程的创建工厂
RejectedExecutionHandler handler 当队列满了后,按照我们指定的拒绝执行策略执行任务
说一个问题,现在核心线程为7,最大线程为20,阻塞队列为50,现在有100个任务进来
核心线程7个处理,然后50个任务进入阻塞队列,然后剩下的13个再次处理,这下就已经处理了70个任务,30个使用拒绝策略
一个线程池 core 7; max 20 ,queue:50,100 并发进来怎么分配的;
先有 7 个能直接得到执行,接下来 50 个进入队列排队,
在多开 13 个继续执行。现在70 个被安排上了。
剩下 30 个默认拒绝策略。
如果不想抛弃还要执行,那就使用同步的方式执行,CallerRunsPolicy;
下面来说异步方法回调:
1.不感知
CompletableFuture<Void> completableFuture=CompletableFuture.runAsync(()->{
System.out.println("不感知结果");
},executorService1);
2.感知结果
CompletableFuture<Integer> completableFuture1=CompletableFuture.supplyAsync(()->{
System.out.println("有感知的方法调用");
return 12;
},executorService1);
3.等待所有线程完成
System.out.println(completableFuture1.get());
CompletableFuture.allOf(completableFuture1,completableFuture).get();