好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

java线程池详解及代码介绍

一.线程池简介

线程池的概念

线程池就是首先创建一些线程,它们的集合称为线程池,使用线程池可以很好的提高性能,线程池在系统启动时既创建大量空闲的线程,程序将一个任务传给线程池。线程池就会启动一条线程来执行这个任务,执行结束后,该线程并不会死亡,而是再次返回线程池中成为空闲状态,等待执行下一个任务。

线程池的工作机制

在线程池的编程模式下,任务是提交给整个线程池,而不是直接提交给某个线程,线程池在拿到任务后,就在内部寻找是否有空闲的线程,如果有,则将任务交给某个空闲的线程

一个线程同时只能执行一个任务,但可以同时向一个线程池提交多个任务

使用线程池的原因

多线程运行时间,系统不断的启动和关闭新线程,成本非常高,会过度消耗系统资源,以及过渡切换线程的危险,从而导致系统资源的崩溃,这时,线程池也就是最好的选择了

二、四种常见的线程池详解

线程池的返回值executorservice简介

executorservice是java提供的用于管理线程池的类。该类的两个作用:控制线程数量和重用线程

具体的4种常用的线程池实现

1-newcachedthreadpool :创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

2-newfixedthreadpool :创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

3-newscheduledthreadpool :创建一个定长线程池,支持定时及周期性任务执行。

4-newsinglethreadexecutor :创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(fifo, lifo, 优先级)执行;

1-executors.newcachethreadpool()

创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。

代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

/**

  * @author: haijiao12138

  * @classname: threadpoolexecutordemo

  * @description: todo   executors.newcachedthreadpool() 创建一个可缓存线程池,如果线程池 长

     度超过处理处理需要,可灵活回收空闲线程  若无可回收 则创建新线程

  *  常见的4种线程池的使用;

  * @date: 2021/8/17 20:17

  */

public class threadpoolexecutordemo {

     public static void main(string[] args) {

         executorservice cachedthreadpool = executors.newcachedthreadpool();

         for ( int i = 0 ; i < 10 ; i++) {

             try {

               thread.sleep( 1 );

             } catch (interruptedexception e) {

                 e.printstacktrace();

             }

             cachedthreadpool.execute( new runnable() {

                 @override

                 public void run() {

                     system.out.println(thread.currentthread().getname()+ "正在被执行" );

                 }

             });

         }

     }

}

运行结果如下:

线程池为无限大,当执行第二个任务时第一个任务已经完成,会复用执行第一个任务的线程,而不用每次新建线程。(用休眠来实现第一个任务完成了);

2-executors.newfixedthreadpool(int n) //括号中存放线程的数量

创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

public class threadpoolexecutordemo {

     public static void main(string[] args) {

         //四种常见的线程池

        /*

         1-newcachedthreadpool(); 创建一个可缓存线程池   如果线程池长度超过处理需要   可灵活回收空闲线程  若无可回收  则新建线程

         2-newfixedthreadpool();  创建一个定长线程池  可控制线程最大并发数  超出的线程 会在队列中等得

         3-newscheduledthreadpool();

         4-newsinglethreadexecutor();

         */

        //第二种线程池

         //2-executors.newfixedthreadpool(int n)

         //创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。

         executorservice fixedthreadpool = executors.newfixedthreadpool( 10 ); //线程池种拥有三个线程

         //创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待

         for ( int i = 0 ; i < 10 ; i++) {

             fixedthreadpool.execute( new runnable() {

                 @override

                 public void run() {

                     try {

                         system.out.println(thread.currentthread().getname()+ "正在执行!" );

                         thread.sleep( 1 );

                     } catch (interruptedexception e) {

                         e.printstacktrace();

                     }

                 }

             });

         }

     }

}

执行代码如下:

3-executors.newscheduledthreadpool(int n);//初始的时候 线程的个数

延迟5秒执行一次:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool( 5 );

        for ( int i = 0 ; i < 3 ; i++) {

            scheduledthreadpool.schedule( new runnable() {

                @override

                public void run() {

                    try {

                        thread.sleep( 1 );

                    } catch (interruptedexception e) {

                        e.printstacktrace();

                    }

                    system.out.println( "延迟5秒执行:" +thread.currentthread().getname());

                }

            }, 5 , timeunit.seconds);

        }

表示延迟1秒后每3秒执行一次:

?

1

2

3

4

5

6

7

8

9

10

public static void main(string[] args) {

        scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool( 5 );

        //延迟1秒执行

        scheduledthreadpool.scheduleatfixedrate( new runnable() {

            @override

            public void run() {

                system.out.println( "延迟1秒后每3秒执行一次:" +thread.currentthread().getname());

            }

        }, 1 , 3 , timeunit.microseconds);

    }

运行结果如下:

4-executors.newsinglethreadexecutor()

创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(fifo, lifo, 优先级)执行。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

public static void main(string[] args) {

     //第四种线程池:

     //executors.newsinglethreadexecutor()

     //创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(fifo, lifo, 优先级)执行。

     //创建一个单线程化的线程池

     executorservice singlethreadexecutor = executors.newsinglethreadexecutor();

     for ( int i = 0 ; i < 10 ; i++) {

         final int index = i;

         singlethreadexecutor.execute( new runnable() {

             @override

             public void run() {

                 try {

                     //结果依次输出,相当于顺序执行各个任务

                     system.out.println(thread.currentthread().getname()+ "正在被执行,打印的值是:" +index);

                     thread.sleep( 1000 );

                 } catch (interruptedexception e) {

                     e.printstacktrace();

                 }

             }

         });

     }

}

结果如下:

三、缓冲队列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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

package com.haijiao12138.demo.leetcode.test0817.缓冲队列;

/**

  * @author: haijiao12138

  * @classname: tempthread

  * @description: todo

  * @date: 2021/8/18 22:24

  */

public class tempthread extends thread {

     @override

     public void run() {

         // 打印正在执行的缓存线程信息

         system.out.println(thread.currentthread().getname() + "正在被执行" );

         try {

             // sleep一秒保证3个任务在分别在3个线程上执行

             thread.sleep( 1000 );

         } catch (interruptedexception e) {

             e.printstacktrace();

         }

     }

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

package com.haijiao12138.demo.leetcode.test0817.缓冲队列;

import java.util.concurrent.arrayblockingqueue;

import java.util.concurrent.blockingqueue;

import java.util.concurrent.threadpoolexecutor;

import java.util.concurrent.timeunit;

/**

  * @author: haijiao12138

  * @classname: testthreadpoolexecutor

  * @description: todo

  * @date: 2021/8/18 22:28

  */

public class testthreadpoolexecutor {

     public static void main(string[] args) {

         // 创建数组型缓冲等待队列

         blockingqueue<runnable> bq = new arrayblockingqueue<runnable>( 10 );

         // threadpoolexecutor:创建自定义线程池,池threadpoolexecutor中保存的线程数为3,允许最大的线程数为6

         threadpoolexecutor tpe = new threadpoolexecutor( 3 , 6 , 50 , timeunit.milliseconds, bq);

         // 创建3个任务

         runnable t1 = new tempthread();

         runnable t2 = new tempthread();

         runnable t3 = new tempthread();

 

         // 3个任务在分别在3个线程上执行

         tpe.execute(t1);

         tpe.execute(t2);

         tpe.execute(t3);

 

         // 关闭自定义线程池

         tpe.shutdown();

     }

}

总结

本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注的更多内容!

原文链接:https://blog.csdn.net/qq_40604313/article/details/119785027

查看更多关于java线程池详解及代码介绍的详细内容...

  阅读:12次