为何用线程池?程序员
在Java中,线程池的概念是Executor这个接口,具体实现为ThreadPoolExecutor类,学习Java中的线程池,就能够直接学习他了对线程池的配置,就是对ThreadPoolExecutor构造函数的参数的配置缓存
//五个参数的构造函数 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) //六个参数的构造函数-1 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) //六个参数的构造函数-2 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) //七个参数的构造函数 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
下面来解释下各个参数:并发
核心线程:线程池新建线程的时候,若是当前线程总数小于corePoolSize,则新建的是核心线程,若是超过corePoolSize,则新建的是非核心线程核心线程默认状况下会一直存活在线程池中,即便这个核心线程啥也不干(闲置状态)。
若是指定ThreadPoolExecutor的allowCoreThreadTimeOut这个属性为true,那么核心线程若是不干活(闲置状态)的话,超过必定时间(时长下面参数决定),就会被销毁掉。ide
线程总数 = 核心线程数 + 非核心线程数。函数
一个非核心线程,若是不干活(闲置状态)的时长超过这个参数所设定的时长,就会被销毁掉,若是设置allowCoreThreadTimeOut = true,则会做用于核心线程。学习
TimeUnit是一个枚举类型,其包括:
NANOSECONDS : 1微毫秒 = 1微秒 / 1000
MICROSECONDS : 1微秒 = 1毫秒 / 1000
MILLISECONDS : 1毫秒 = 1秒 /1000
SECONDS : 秒
MINUTES : 分
HOURS : 小时
DAYS : 天spa
当全部的核心线程都在干活时,新添加的任务会被添加到这个队列中等待处理,若是队列满了,则新建非核心线程执行任务。
经常使用的workQueue类型:线程
SynchronousQueue:这个队列接收到任务的时候,会直接提交给线程处理,而不保留它,若是全部线程都在工做怎么办?那就新建一个线程来处理这个任务!因此为了保证不出现<线程数达到了maximumPoolSize而不能新建线程>的错误,使用这个类型队列的时候,maximumPoolSize通常指定成Integer.MAX_VALUE,即无限大code
LinkedBlockingQueue:这个队列接收到任务的时候,若是当前线程数小于核心线程数,则新建线程(核心线程)处理任务;若是当前线程数等于核心线程数,则进入队列等待。因为这个队列没有最大值限制,即全部超过核心线程数的任务都将被添加到队列中,这也就致使了maximumPoolSize的设定失效,由于总线程数永远不会超过corePoolSize对象
ArrayBlockingQueue:能够限定队列的长度,接收到任务的时候,若是没有达到corePoolSize的值,则新建线程(核心线程)执行任务,若是达到了,则入队等候,若是队列已满,则新建线程(非核心线程)执行任务,又若是总线程数到了maximumPoolSize,而且队列也满了,则发生错误
DelayQueue:队列内元素必须实现Delayed接口,这就意味着你传进去的任务必须先实现Delayed接口。这个队列接收到任务时,首先先入队,只有达到了指定的延时时间,才会执行任务
ThreadFactory threadFactory:建立线程的方式,这是一个接口,你new他的时候须要实现他的Thread newThread(Runnable r)方法,通常用不上。
RejectedExecutionHandler handler:这玩意儿就是抛出异常专用的,好比上面提到的两个错误发生了,就会由这个handler抛出异常,根本用不上。
咱们怎么知道new一个ThreadPoolExecutor,大概知道各个参数是干吗的,但是我new完了,怎么向线程池提交一个要执行的任务啊?
ThreadPoolExecutor.execute(Runnable command)
经过ThreadPoolExecutor.execute(Runnable command)方法便可向线程池内添加一个任务。
这里给总结一下,当一个任务被添加进线程池时,执行策略:
+++++++++++++++++++++++++++我是分割线++++++++++++++++++++++++++++
若是你不想本身写一个线程池,Java经过Executors提供了四种线程池,这四种线程池都是直接或间接配置ThreadPoolExecutor的参数实现的。
1.可缓存线程池CachedThreadPool()
源码:
public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
根据源码能够看出:
建立方法:
ExecutorService mCachedThreadPool = Executors.newCachedThreadPool();
用法:
//开始下载 private void startDownload(final ProgressBar progressBar, final int i) { mCachedThreadPool.execute(new Runnable() { @Override public void run() { int p = 0; progressBar.setMax(10);//每一个下载任务10秒 while (p < 10) { p++; progressBar.setProgress(p); Bundle bundle = new Bundle(); Message message = new Message(); bundle.putInt("p", p); //把当前线程的名字用handler让textview显示出来 bundle.putString("ThreadName", Thread.currentThread().getName()); message.what = i; message.setData(bundle); mHandler.sendMessage(message); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }); }
2.FixedThreadPool 定长线程池
源码:
public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
根据源码能够看出:
建立方法:
//nThreads => 最大线程数即maximumPoolSize ExecutorService mFixedThreadPool= Executors.newFixedThreadPool(int nThreads); //threadFactory => 建立线程的方法,用得少 ExecutorService mFixedThreadPool= Executors.newFixedThreadPool(int nThreads, ThreadFactory threadFactory);
用法:
private void startDownload(final ProgressBar progressBar, final int i) { mFixedThreadPool.execute(new Runnable() { @Override public void run() { //....逻辑代码本身控制 } }); }
3.SingleThreadPool
源码:
public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
根据源码能够看出:
建立方法:
ExecutorService mSingleThreadPool = Executors.newSingleThreadPool();
用法同上。
4.ScheduledThreadPool
源码:
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) { return new ScheduledThreadPoolExecutor(corePoolSize); } //ScheduledThreadPoolExecutor(): public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS, new DelayedWorkQueue()); }
根据源码能够看出:
DEFAULT_KEEPALIVE_MILLIS就是默认10L,这里就是10秒。这个线程池有点像是吧CachedThreadPool和FixedThreadPool 结合了一下。
建立:
//nThreads => 最大线程数即maximumPoolSize ExecutorService mScheduledThreadPool = Executors.newScheduledThreadPool(int corePoolSize);
通常的执行任务方法和上面的都大同小异,咱们主要看看延时执行任务和周期执行任务的方法。
//表示在3秒以后开始执行咱们的任务。 mScheduledThreadPool.schedule(new Runnable() { @Override public void run() { //.... } }, 3, TimeUnit.SECONDS);
//延迟3秒后执行任务,从开始执行任务这个时候开始计时,每7秒执行一次无论执行任务须要多长的时间。 mScheduledThreadPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { //.... } },3, 7, TimeUnit.SECONDS);
/**延迟3秒后执行任务,从任务完成时这个时候开始计时,7秒后再执行, *再等完成后计时7秒再执行也就是说这里的循环执行任务的时间点是 *从上一个任务完成的时候。 */ mScheduledThreadPool.scheduleWithFixedDelay(new Runnable() { @Override public void run() { //.... } },3, 7, TimeUnit.SECONDS);
以上就是经常使用的四个线程池以及他们的实现原理。
做者:我弟是个程序员 连接:https://www.jianshu.com/p/ae67972d1156 來源:简书 简书著做权归做者全部,任何形式的转载都请联系做者得到受权并注明出处。