常用的4种线程池介绍

         <!--一个博主专栏付费入口结束-->
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-d284373521.css">
                                    <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-d284373521.css">
            <div class="htmledit_views" id="content_views">
                                        <h1><a name="t0"></a>一. 线程池简介</h1><p>1. 线程池的概念:</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 线程池就是首先创建一些线程,它们的集合称为线程池。使用线程池可以很好地提高性能,线程池在系统启动时即创建大量空闲的线程,程序将一个任务传给线程池,线程池就会启动一条线程来执行这个任务,执行结束以后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个任务。</p><p>2. 线程池的工作机制</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2.1 在线程池的编程模式下,任务是提交给整个线程池,而不是直接提交给某个线程,线程池在拿到任务后,就在内部寻找是否有空闲的线程,如果有,则将任务交给某个空闲的线程。</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2.1 一个线程同时只能执行一个任务,但可以同时向一个线程池提交多个任务。</p><p>3. 使用线程池的原因:</p><p>&nbsp; &nbsp; &nbsp; &nbsp; 多线程运行时间,系统不断的启动和关闭新线程,成本非常高,会过渡消耗系统资源,以及过渡切换线程的危险,从而可能导致系统资源的崩溃。这时,线程池就是最好的选择了。</p><h1><a name="t1"></a>二. 四种常见的线程池详解</h1><p>1. 线程池的返回值ExecutorService简介:</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ExecutorService是Java提供的用于管理线程池的类。该类的两个作用:控制线程数量和重用线程</p><p>2. 具体的4种常用的线程池实现如下:(返回值都是ExecutorService)</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;2.1 Executors.newCacheThreadPool():可缓存线程池,先查看池中有没有以前建立的线程,如果有,就直接使用。如果没有,就建一个新的线程加入池中,缓存型池子通常用于执行一些生存期很短的异步型任务</p><p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;示例代码:</p><div class="cnblogs_code"><img class="code_img_opened" src="https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif" alt=""><div class="cnblogs_code_hide"><div class="cnblogs_code_toolbar"><span class="cnblogs_code_copy"><a title="复制代码"><img src="https://i-blog.csdnimg.cn/blog_migrate/48304ba5e6f9fe08f3fa1abda7d326ab.gif" alt="复制代码"></a></span></div><pre><span style="color:#008080;"> 1</span> <span style="color:#0000ff;">package</span><span style="color:#000000;"> 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秒执行

             定期执行示例代码:

复制代码
 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

1. 缓冲队列BlockingQueue简介:

          BlockingQueue是双缓冲队列。BlockingQueue内部使用两条队列,允许两个线程同时向队列一个存储,一个取出操作。在保证并发安全的同时,提高了队列的存取效率。

2. 常用的几种BlockingQueue:

  • ArrayBlockingQueue(int i):规定大小的BlockingQueue,其构造必须指定大小。其所含的对象是FIFO顺序排序的。

  • LinkedBlockingQueue()或者(int i):大小不固定的BlockingQueue,若其构造时指定大小,生成的BlockingQueue有大小限制,不指定大小,其大小有Integer.MAX_VALUE来决定。其所含的对象是FIFO顺序排序的。

  • PriorityBlockingQueue()或者(int i):类似于LinkedBlockingQueue,但是其所含对象的排序不是FIFO,而是依据对象的自然顺序或者构造函数的Comparator决定。

  • SynchronizedQueue():特殊的BlockingQueue,对其的操作必须是放和取交替完成。

3. 自定义线程池(ThreadPoolExecutor和BlockingQueue连用):

     自定义线程池,可以用ThreadPoolExecutor类创建,它有多个构造方法来创建线程池。

    常见的构造函数:ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> 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正在被执行


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值