一. 线程池简介java
线程池的概念:编程
线程池就是首先建立一些线程,它们的集合称为线程池。使用线程池能够很好地提升性能,线程池在系统启动时即建立大量空闲的线程,程序将一个任务传给线程池,线程池就会启动一条线程来执行这个任务,执行结束之后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个任务。
复制代码
线程池的工做机制数组
2.1 在线程池的编程模式下,任务是提交给整个线程池,而不是直接提交给某个线程,线程池在拿到任务后,就在内部寻找是否有空闲的线程,若是有,则将任务交给某个空闲的线程。
2.1 一个线程同时只能执行一个任务,但能够同时向一个线程池提交多个任务。
复制代码
使用线程池的缘由:缓存
多线程运行时间,系统不断的启动和关闭新线程,成本很是高,会过渡消耗系统资源,以及过渡切换线程的危险,从而可能致使系统资源的崩溃。这时,线程池就是最好的选择了。
复制代码
二. 四种常见的线程池详解安全
线程池的返回值ExecutorService简介:bash
ExecutorService是Java提供的用于管理线程池的类。该类的两个做用:控制线程数量和重用线程
复制代码
具体的4种经常使用的线程池实现以下:(返回值都是ExecutorService)多线程
2.1 Executors.newCacheThreadPool():可缓存线程池,先查看池中有没有之前创建的线程,若是有,就直接使用。若是没有,就建一个新的线程加入池中,缓存型池子一般用于执行一些生存期很短的异步型任务
示例代码:
复制代码
1 package com.study.test;
2
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.Executors;
5
6 public class ThreadPoolExecutorTest {
7 public static void main(String[] args) {
8 //建立一个可缓存线程池
9 ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
10 for (int i = 0; i < 10; i++) {
11 try {
12 //sleep可明显看到使用的是线程池里面之前的线程,没有建立新的线程
13 Thread.sleep(1000);
14 } catch (InterruptedException e) {
15 e.printStackTrace();
16 }
17 cachedThreadPool.execute(new Runnable() {
18 public void run() {
19 //打印正在执行的缓存线程信息
20 System.out.println(Thread.currentThread().getName()+"正在被执行");
21 }
22 });
23 }
24 }
25 }
复制代码
输出结果:
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
pool-1-thread-1正在被执行
复制代码
线程池为无限大,当执行当前任务时上一个任务已经完成,会复用执行上一个任务的线程,而不用每次新建线程并发
2.2 Executors.newFixedThreadPool(int n):建立一个可重用固定个数的线程池,以共享的无界队列方式来运行这些线程。
示例代码:
复制代码
1 package com.study.test;
2
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.Executors;
5
6 public class ThreadPoolExecutorTest {
7 public static void main(String[] args) {
8 //建立一个可重用固定个数的线程池
9 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
10 for (int i = 0; i < 10; i++) {
11 fixedThreadPool.execute(new Runnable() {
12 public void run() {
13 try {
14 //打印正在执行的缓存线程信息
15 System.out.println(Thread.currentThread().getName()+"正在被执行");
16 Thread.sleep(2000);
17 } catch (InterruptedException e) {
18 e.printStackTrace();
19 }
20 }
21 });
22 }
23 }
24 }
复制代码
输出结果:
pool-1-thread-1正在被执行
pool-1-thread-2正在被执行
pool-1-thread-3正在被执行
pool-1-thread-1正在被执行
pool-1-thread-2正在被执行
pool-1-thread-3正在被执行
pool-1-thread-1正在被执行
pool-1-thread-2正在被执行
pool-1-thread-3正在被执行
pool-1-thread-1正在被执行
复制代码
由于线程池大小为3,每一个任务输出打印结果后sleep 2秒,因此每两秒打印3个结果。 定长线程池的大小最好根据系统资源进行设置。如Runtime.getRuntime().availableProcessors()异步
2.3 Executors.newScheduledThreadPool(int n):建立一个定长线程池,支持定时及周期性任务执行
延迟执行示例代码:
复制代码
1 package com.study.test;
2
3 import java.util.concurrent.Executors;
4 import java.util.concurrent.ScheduledExecutorService;
5 import java.util.concurrent.TimeUnit;
6
7 public class ThreadPoolExecutorTest {
8 public static void main(String[] args) {
9 //建立一个定长线程池,支持定时及周期性任务执行——延迟执行
10 ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
11 //延迟1秒执行
12 scheduledThreadPool.schedule(new Runnable() {
13 public void run() {
14 System.out.println("延迟1秒执行");
15 }
16 }, 1, TimeUnit.SECONDS);
17 }
18 }
复制代码
输出结果:延迟1秒执行ide
按期执行示例代码:
复制代码
1 package com.study.test;
2
3 import java.util.concurrent.Executors;
4 import java.util.concurrent.ScheduledExecutorService;
5 import java.util.concurrent.TimeUnit;
6
7 public class ThreadPoolExecutorTest {
8 public static void main(String[] args) {
9 //建立一个定长线程池,支持定时及周期性任务执行——按期执行
10 ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
11 //延迟1秒后每3秒执行一次
12 scheduledThreadPool.scheduleAtFixedRate(new Runnable() {
13 public void run() {
14 System.out.println("延迟1秒后每3秒执行一次");
15 }
16 }, 1, 3, TimeUnit.SECONDS);
17 }
18 }
复制代码
输出结果:
延迟1秒后每3秒执行一次 延迟1秒后每3秒执行一次 .............
2.4 Executors.newSingleThreadExecutor():建立一个单线程化的线程池,它只会用惟一的工做线程来执行任务,保证全部任务按照指定顺序(FIFO, LIFO, 优先级)执行。
示例代码:
复制代码
1 package com.study.test;
2
3 import java.util.concurrent.ExecutorService;
4 import java.util.concurrent.Executors;
5
6 public class TestThreadPoolExecutor {
7 public static void main(String[] args) {
8 //建立一个单线程化的线程池
9 ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
10 for (int i = 0; i < 10; i++) {
11 final int index = i;
12 singleThreadExecutor.execute(new Runnable() {
13 public void run() {
14 try {
15 //结果依次输出,至关于顺序执行各个任务
16 System.out.println(Thread.currentThread().getName()+"正在被执行,打印的值是:"+index);
17 Thread.sleep(1000);
18 } catch (InterruptedException e) {
19 e.printStackTrace();
20 }
21 }
22 });
23 }
24 }
25 }
复制代码
输出结果:
pool-1-thread-1正在被执行,打印的值是:0
pool-1-thread-1正在被执行,打印的值是:1
pool-1-thread-1正在被执行,打印的值是:2
pool-1-thread-1正在被执行,打印的值是:3
pool-1-thread-1正在被执行,打印的值是:4
pool-1-thread-1正在被执行,打印的值是:5
pool-1-thread-1正在被执行,打印的值是:6
pool-1-thread-1正在被执行,打印的值是:7
pool-1-thread-1正在被执行,打印的值是:8
pool-1-thread-1正在被执行,打印的值是:9
复制代码
三. 缓冲队列BlockingQueue和自定义线程池ThreadPoolExecutor
缓冲队列BlockingQueue简介:
BlockingQueue是双缓冲队列。BlockingQueue内部使用两条队列,容许两个线程同时向队列一个存储,一个取出操做。在保证并发安全的同时,提升了队列的存取效率。
复制代码
经常使用的几种BlockingQueue:
ArrayBlockingQueue(int i):规定大小的BlockingQueue,其构造必须指定大小。其所含的对象是FIFO顺序排序的。
LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue,若其构造时指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE来决定。其所含的对象是FIFO顺序排序的。
PriorityBlockingQueue()或者(int i):相似于LinkedBlockingQueue,可是其所含对象的排序不是FIFO,而是依据对象的天然顺序或者构造函数的Comparator决定。
SynchronizedQueue():特殊的BlockingQueue,对其的操做必须是放和取交替完成。
自定义线程池(ThreadPoolExecutor和BlockingQueue连用):
自定义线程池,能够用ThreadPoolExecutor类建立,它有多个构造方法来建立线程池。
常见的构造函数:ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue workQueue)
示例代码:
1 package com.study.test;
2
3 import java.util.concurrent.ArrayBlockingQueue;
4 import java.util.concurrent.BlockingQueue;
5 import java.util.concurrent.ThreadPoolExecutor;
6 import java.util.concurrent.TimeUnit;
7
8 class TempThread implements Runnable {
9
10 @Override
11 public void run() {
12 // 打印正在执行的缓存线程信息
13 System.out.println(Thread.currentThread().getName() + "正在被执行");
14 try {
15 // sleep一秒保证3个任务在分别在3个线程上执行
16 Thread.sleep(1000);
17 } catch (InterruptedException e) {
18 e.printStackTrace();
19 }
20 }
21
22 }
23
24 public class TestThreadPoolExecutor {
25 public static void main(String[] args) {
26 // 建立数组型缓冲等待队列
27 BlockingQueue<Runnable> bq = new ArrayBlockingQueue<Runnable>(10);
28 // ThreadPoolExecutor:建立自定义线程池,池中保存的线程数为3,容许最大的线程数为6
29 ThreadPoolExecutor tpe = new ThreadPoolExecutor(3, 6, 50, TimeUnit.MILLISECONDS, bq);
30
31 // 建立3个任务
32 Runnable t1 = new TempThread();
33 Runnable t2 = new TempThread();
34 Runnable t3 = new TempThread();
35 // Runnable t4 = new TempThread();
36 // Runnable t5 = new TempThread();
37 // Runnable t6 = new TempThread();
38
39 // 3个任务在分别在3个线程上执行
40 tpe.execute(t1);
41 tpe.execute(t2);
42 tpe.execute(t3);
43 // tpe.execute(t4);
44 // tpe.execute(t5);
45 // tpe.execute(t6);
46
47 // 关闭自定义线程池
48 tpe.shutdown();
49 }
50 }
复制代码
输出结果:
pool-1-thread-1正在被执行
pool-1-thread-2正在被执行
pool-1-thread-3正在被执行
复制代码
note:人生老是有取有舍的,为了本身想过的生活,勇敢放弃一些东西。淡定的人,善待生命,沉稳而不缺乏热情;淡定的人,处事不惊,安详而不缺少快意。淡定的人生,历尽沧桑,却依然呈现随遇而安的美丽淡然。