yd记录

如何上传patch?怎么打包的?

答案就是git操作之类

多线程方式

线程池有哪几种

Spring怎么配置线程池  :Spring通过ThreadPoolTaskExecutor实现线程池技术,它是使用jdk中的Java.util.concurrent.ThreadPoolExecutor(第二种,不是第一种Excutor框架的工具类来new)进行实现

核心线程数5,最大线程数10,工作队列有100个怎么办?应该是问饱和(拒绝)策略没答上来

现在出去面试,多线程以及并发变成已经成为了必问的问题。 今天就来总结下多线程在项目中的应用以及线程池的使用。
多线程的使用: 比如在庞大的项目中,一个请求中,可能要调用N 多个服务, 比如调用积分服务,订单服务,地址服务,库存服务或者一些其他公司的服务等,每次调用过程中如果每个服务都用500ms,那么整体的时长就是n*500。so,这个时间是无法忍受的, 所以就要使用多线程来干这个事情了。 为了提高线程的使用率,避免造成性能的浪费, 所以这里就要用到线程池了,
这里来说说线程池:众所周知,线程池就是来管理线程的容器。

第一种:

一般的面试这就会说:newCachedThreadPool,newFixedThreadPool,newSingleThreadExecutornewScheduleThreadPool四种线程池, 然后再分别说下这些个线程池的意义。

但通过Excutor框架的工具类Excutors.newCachedThreadPool等上面四个类会有OOM的风险。

第二种:

骨灰级的玩家就会说: 线程池核心的东西就是一个ThreadPoolExecutor类(推荐用这个类的不同构造方法来新建线程池,规避资源耗尽的风险),然后ThreadPoolExecutor 里面有四个构造函数,通过这四个构造函数创建线程池,他有几个参数很重要。 
1.public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), defaultHandler);
}

2.public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
threadFactory, defaultHandler);
}

3.public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
RejectedExecutionHandler handler) {
this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue,
Executors.defaultThreadFactory(), handler);
}

4.public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit
unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
这里对这些参数做做个解释:
corePoolSize;核心线程数, 当任务数量超过了核心线程数,任务就会放入队列中
maximumPoolSize:最大线程数量, 当任务数量超过了最大线程数量,队列也满了, 就会执行拒绝策略,
keepAliveTime;存活时间, 当非核心线程没活干的时候, 还能活多久
unit:时间单位
workQueue:消息队列, 用来存任务, 一般有 : ArrayBlockingQueue,LinkedBlockingQueue,SynchronousQueue一般使用 LinkedBlockingQueue
threadFactory:线程工厂, 用来创建线程池
handler: 处理器, 表示拒绝策略,最大线程数量也满了的时候。 一般有四种:ThreadPoolExecutor.AbortPolicy:ThreadPoolExecutor类丢弃任务并抛出RejectedExecutionException异常;ThreadPoolExecutor.CallerRunsPolicy:不丢弃任何一个任务,扩大工作队列(提供可伸缩的工作队列);ThreadPoolExecutor.DiscardPolicy:不处理新任务,直接丢弃;ThreadPoolExecutor.DiscardOldestPolicy:丢弃最早未处理的线程。

 

posted @ 2020-11-02 11:37  xinxinpang  阅读(67)  评论(0编辑  收藏  举报