为何要使用线程池?java
(1)下降资源消耗。经过重复利用已建立的线程下降线程建立和销毁形成的消耗。缓存
(2)提升响应速度。当任务到达时,任务能够不须要等到线程建立就能当即执行。ide
(3)提升线程的可管理性。线程是稀缺资源,若是无限制的建立,不只会消耗系统资源,还会下降系统的稳定性,使用线程池能够进行统一的分配,调优和监控。this
建立和使用线程池:
线程
在java中咱们可使用new ThreadPoolExecutor(...) 来建立线程池code
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory(), defaultHandler); } corePoolSize - 池中所保存的线程数,包括空闲线程。 maximumPoolSize - 池中容许的最大线程数。 keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。 unit - keepAliveTime 参数的时间单位。 workQueue - 执行前用于保持任务的队列。此队列仅保持由 execute 方法提交的 Runnable 任务。
通常状况下咱们不用自定义线程池,java中提供了大量建立链接池的静态方法,接下来咱们来介绍经常使用的几种:队列
首先看一下线程池的类图结构:资源
(1)固定大小的线程池 get
ExecutorService pool = Executors.newFixedThreadPool(10)it
(2)单线程化的线程池
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor()
(3)可缓存线程池
ExecutorService cachedThreadPool = Executors.newCachedThreadPool
(4)一个定长线程池,支持定时及周期性任务执行
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
简单实用线程池例子:
public class ThreadPoolTest { public static void main(String[] args) { // 固定大小线程池 ExecutorService pool = Executors.newFixedThreadPool(2); //建立5个线程 Thread t1 = new MyThread(); Thread t2 = new MyThread(); Thread t3 = new MyThread(); Thread t4 = new MyThread(); Thread t5 = new MyThread(); //将线程放入线程池 pool.execute(t1); pool.execute(t2); pool.execute(t3); pool.execute(t4); pool.execute(t5); //关闭线程池 pool.shutdown(); } } class MyThread extends Thread { @Override public void run() { System.out.println(Thread.currentThread().getName() + "正在执行。。。"); } } //执行结果 pool-1-thread-1正在执行。。。 pool-1-thread-2正在执行。。。 pool-1-thread-1正在执行。。。 pool-1-thread-2正在执行。。。 pool-1-thread-1正在执行。。。