好得很程序员自学网

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

Java四种常用线程池的详细介绍

一. 线程池简介

1. 线程池的概念:

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

2. 线程池的工作机制

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

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

3. 使用线程池的原因:

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

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

1. 线程池的返回值executorservice简介:

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

2. 具体的4种常用的线程池实现如下:(返回值都是executorservice)

2.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

package com.study.test;

import java.util.concurrent.executorservice;

import java.util.concurrent.executors;

public class threadpoolexecutortest {

   public static void main(string[] args) {

    //创建一个可缓存线程池

    executorservice cachedthreadpool = executors.newcachedthreadpool();

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

      try {

        //sleep可明显看到使用的是线程池里面以前的线程,没有创建新的线程

        thread.sleep( 1000 );

      } catch (interruptedexception e) {

        e.printstacktrace();

       }

      cachedthreadpool.execute( new runnable() {

        public void run() {

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

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

        }

       });

     }

   }

}

输出结果:

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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

package com.study.test;

import java.util.concurrent.executorservice;

import java.util.concurrent.executors;

public class threadpoolexecutortest {

  public static void main(string[] args) {

     //创建一个可重用固定个数的线程池

     executorservice fixedthreadpool = executors.newfixedthreadpool( 3 );

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

      fixedthreadpool.execute( new runnable() {

         public void run() {

           try {

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

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

            thread.sleep( 2000 );

          } catch (interruptedexception e) {

            e.printstacktrace();

           }

         }

      });

     }

   }

}

输出结果:

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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package com.study.test;

import java.util.concurrent.executors;

import java.util.concurrent.scheduledexecutorservice;

import java.util.concurrent.timeunit;

public class threadpoolexecutortest {

   public static void main(string[] args) {

     //创建一个定长线程池,支持定时及周期性任务执行——延迟执行

     scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool( 5 );

     //延迟1秒执行

     scheduledthreadpool.schedule( new runnable() {

       public void run() {

         system.out.println( "延迟1秒执行" );

       }

     }, 1 , timeunit.seconds);

    }

}

输出结果:

延迟1秒执行

定期执行示例代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

package com.study.test;

import java.util.concurrent.executors;

import java.util.concurrent.scheduledexecutorservice;

import java.util.concurrent.timeunit;

public class threadpoolexecutortest {

   public static void main(string[] args) {

     //创建一个定长线程池,支持定时及周期性任务执行——定期执行

     scheduledexecutorservice scheduledthreadpool = executors.newscheduledthreadpool( 5 );

     //延迟1秒后每3秒执行一次

     scheduledthreadpool.scheduleatfixedrate( new runnable() {

        public void run() {

         system.out.println( "延迟1秒后每3秒执行一次" );

       }

     }, 1 , 3 , timeunit.seconds);

   }

}

输出结果:

延迟1秒后每3秒执行一次
延迟1秒后每3秒执行一次
.............

2.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

23

package com.study.test;

import java.util.concurrent.executorservice;

import java.util.concurrent.executors;

public class testthreadpoolexecutor {

   public static void main(string[] args) {

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

     executorservice singlethreadexecutor = executors.newsinglethreadexecutor();

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

       final int index = i;

        singlethreadexecutor.execute( new runnable() {

         public void run() {

           try {

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

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

             thread.sleep( 1000 );

           } catch (interruptedexception e) {

              e.printstacktrace();

           }

         }

        });

     }

    }

}

输出结果:

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

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

32

33

34

35

36

37

38

39

40

41

42

package com.study.test;

import java.util.concurrent.arrayblockingqueue;

import java.util.concurrent.blockingqueue;

import java.util.concurrent.threadpoolexecutor;

import java.util.concurrent.timeunit;

class tempthread implements runnable {

   @override

   public void run() {

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

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

      try {

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

       thread.sleep( 1000 );

      } catch (interruptedexception e) {

        e.printstacktrace();

     }

    }

}

public class testthreadpoolexecutor {

   public static void main(string[] args) {

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

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

     // 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();

      // runnable t4 = new tempthread();

      // runnable t5 = new tempthread();

      // runnable t6 = new tempthread();

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

      tpe.execute(t1);

      tpe.execute(t2);

      tpe.execute(t3);

      // tpe.execute(t4);

      // tpe.execute(t5);

      // tpe.execute(t6);

      // 关闭自定义线程池

      tpe.shutdown();

    }

}

输出结果:

pool-1-thread-1正在被执行
pool-1-thread-2正在被执行
pool-1-thread-3正在被执行

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/hnd978142833/article/details/80253784

查看更多关于Java四种常用线程池的详细介绍的详细内容...

  阅读:13次