你的位置:首页 > 软件开发 > Java > 编写高质量代码:改善Java程序的151个建议(第8章:多线程和并发___建议126~128)

编写高质量代码:改善Java程序的151个建议(第8章:多线程和并发___建议126~128)

发布时间:2016-10-19 17:00:14
建议126:适时选择不同的线程池来实现  Java的线程池实现从根本上来说只有两个:ThreadPoolExecutor类和ScheduledThreadPoolExecutor类,这两个类还是父子关系,但是Java为了简化并行计算,还提供了一个Exceutors的静态类,它可以 ...

建议126:适时选择不同的线程池来实现

  Java的线程池实现从根本上来说只有两个:ThreadPoolExecutor类和ScheduledThreadPoolExecutor类,这两个类还是父子关系,但是Java为了简化并行计算,还提供了一个Exceutors的静态类,它可以直接生成多种不同的线程池执行器,比如单线程执行器、带缓冲功能的执行器等,但归根结底还是使用ThreadPoolExecutor类或ScheduledThreadPoolExecutor类的封装类。

  为了理解这些执行器,我们首先来看看ThreadPoolExecutor类,其中它复杂的构造函数可以很好的理解线程池的作用,代码如下:  

public class ThreadPoolExecutor extends AbstractExecutorService {  // 最完整的构造函数  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;  }}
        ***开始执行 TaskWithSync 任务***

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:编写高质量代码:改善Java程序的151个建议(第8章:多线程和并发___建议126~128)

关键词:JAVA

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。