线程池ThreadPoolExecutor使用简介与方法实例

2025-05-29 0 53

一、简介

线程池类为 java.util.concurrent.threadpoolexecutor,常用构造方法为:

?

1

2

3

4
threadpoolexecutor(int corepoolsize, int maximumpoolsize,

long keepalivetime, timeunit unit,

blockingqueue workqueue,

rejectedexecutionhandler handler)

  • corepoolsize: 线程池维护线程的最少数量
  • maximumpoolsize:线程池维护线程的最大数量
  • keepalivetime: 线程池维护线程所允许的空闲时间
  • unit: 线程池维护线程所允许的空闲时间的单位
  • workqueue: 线程池所使用的缓冲队列
  • handler: 线程池对拒绝任务的处理策略

一个任务通过 execute(runnable)方法被添加到线程池,任务就是一个 runnable类型的对象,任务的执行方法就是 runnable类型对象的run()方法。

当一个任务通过execute(runnable)方法欲添加到线程池时:

  • 如果此时线程池中的数量小于corepoolsize,即使线程池中的线程都处于空闲状态,也要创建新的线程来处理被添加的任务。
  • 如果此时线程池中的数量等于 corepoolsize,但是缓冲队列 workqueue未满,那么任务被放入缓冲队列。
  • 如果此时线程池中的数量大于corepoolsize,缓冲队列workqueue满,并且线程池中的数量小于maximumpoolsize,建新的线程来处理被添加的任务。
  • 如果此时线程池中的数量大于corepoolsize,缓冲队列workqueue满,并且线程池中的数量等于maximumpoolsize,那么通过 handler所指定的策略来处理此任务。

也就是:处理任务的优先级为:

核心线程corepoolsize、任务队列workqueue、最大线程maximumpoolsize,如果三者都满了,使用handler处理被拒绝的任务。

线程池中的线程数量大于 corepoolsize时,如果某线程空闲时间超过keepalivetime,线程将被终止。这样,线程池可以动态的调整池中的线程数。

unit可选的参数为java.util.concurrent.timeunit中的几个静态属性:

nanoseconds、microseconds、milliseconds、seconds。

workqueue我常用的是:java.util.concurrent.arrayblockingqueue

handler有四个选择:

  • threadpoolexecutor.abortpolicy() 抛出java.util.concurrent.rejectedexecutionexception异常
  • threadpoolexecutor.callerrunspolicy() 重试添加当前的任务,他会自动重复调用execute()方法
  • threadpoolexecutor.discardoldestpolicy() 抛弃旧的任务
  • threadpoolexecutor.discardpolicy() 抛弃当前的任务

二、一般用法举例

?

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

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66
package demo;

import java.io.serializable;

import java.util.concurrent.arrayblockingqueue;

import java.util.concurrent.threadpoolexecutor;

import java.util.concurrent.timeunit;

public class testthreadpool2

{

private static int producetasksleeptime = 2;

private static int producetaskmaxnumber = 10;

public static void main(string[] args)

{

// 构造一个线程池

threadpoolexecutor threadpool = new threadpoolexecutor(2, 4, 3, timeunit.seconds, new arrayblockingqueue<runnable>(3),

new threadpoolexecutor.discardoldestpolicy());

for (int i = 1; i <= producetaskmaxnumber; i++)

{

try

{

// 产生一个任务,并将其加入到线程池

string task = "task@ " + i;

system.out.println("put " + task);

threadpool.execute(new threadpooltask(task));

// 便于观察,等待一段时间

thread.sleep(producetasksleeptime);

}

catch (exception e)

{

e.printstacktrace();

}

}

}

}

/**

* 线程池执行的任务

*/

class threadpooltask implements runnable, serializable

{

private static final long serialversionuid = 0;

private static int consumetasksleeptime = 2000;

// 保存任务所需要的数据

private object threadpooltaskdata;

threadpooltask(object tasks)

{

this.threadpooltaskdata = tasks;

}

public void run()

{

// 处理一个任务,这里的处理方式太简单了,仅仅是一个打印语句

system.out.println(thread.currentthread().getname());

system.out.println("start .." + threadpooltaskdata);

try

{

// //便于观察,等待一段时间

thread.sleep(consumetasksleeptime);

}

catch (exception e)

{

e.printstacktrace();

}

threadpooltaskdata = null;

}

public object gettask()

{

return this.threadpooltaskdata;

}

}

说明:

1、在这段程序中,一个任务就是一个runnable类型的对象,也就是一个threadpooltask类型的对象。

2、一般来说任务除了处理方式外,还需要处理的数据,处理的数据通过构造方法传给任务。

3、在这段程序中,main()方法相当于一个残忍的领导,他派发出许多任务,丢给一个叫 threadpool的任劳任怨的小组来做。

这个小组里面队员至少有两个,如果他们两个忙不过来,任务就被放到任务列表里面。

如果积压的任务过多,多到任务列表都装不下(超过3个)的时候,就雇佣新的队员来帮忙。但是基于成本的考虑,不能雇佣太多的队员,至多只能雇佣 4个。

如果四个队员都在忙时,再有新的任务,这个小组就处理不了了,任务就会被通过一种策略来处理,我们的处理方式是不停的派发,直到接受这个任务为止(更残忍!呵呵)。

因为队员工作是需要成本的,如果工作很闲,闲到 3seconds都没有新的任务了,那么有的队员就会被解雇了,但是,为了小组的正常运转,即使工作再闲,小组的队员也不能少于两个。

4、通过调整 producetasksleeptime和 consumetasksleeptime的大小来实现对派发任务和处理任务的速度的控制,改变这两个值就可以观察不同速率下程序的工作情况。

5、通过调整4中所指的数据,再加上调整任务丢弃策略,换上其他三种策略,就可以看出不同策略下的不同处理方式。

6、对于其他的使用方法,参看jdk的帮助,很容易理解和使用。

另一个例子:

?

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

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76
package demo;

import java.util.queue;

import java.util.concurrent.arrayblockingqueue;

import java.util.concurrent.threadpoolexecutor;

import java.util.concurrent.timeunit;

public class threadpoolexecutortest

{

private static int queuedeep = 4;

public void createthreadpool()

{

/*

* 创建线程池,最小线程数为2,最大线程数为4,线程池维护线程的空闲时间为3秒,

* 使用队列深度为4的有界队列,如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,

* 然后重试执行程序(如果再次失败,则重复此过程),里面已经根据队列深度对任务加载进行了控制。

*/

threadpoolexecutor tpe = new threadpoolexecutor(2, 4, 3, timeunit.seconds, new arrayblockingqueue<runnable>(queuedeep),

new threadpoolexecutor.discardoldestpolicy());

// 向线程池中添加 10 个任务

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

{

try

{

thread.sleep(1);

}

catch (interruptedexception e)

{

e.printstacktrace();

}

while (getqueuesize(tpe.getqueue()) >= queuedeep)

{

system.out.println("队列已满,等3秒再添加任务");

try

{

thread.sleep(3000);

}

catch (interruptedexception e)

{

e.printstacktrace();

}

}

taskthreadpool ttp = new taskthreadpool(i);

system.out.println("put i:" + i);

tpe.execute(ttp);

}

tpe.shutdown();

}

private synchronized int getqueuesize(queue queue)

{

return queue.size();

}

public static void main(string[] args)

{

threadpoolexecutortest test = new threadpoolexecutortest();

test.createthreadpool();

}

class taskthreadpool implements runnable

{

private int index;

public taskthreadpool(int index)

{

this.index = index;

}

public void run()

{

system.out.println(thread.currentthread() + " index:" + index);

try

{

thread.sleep(3000);

}

catch (interruptedexception e)

{

e.printstacktrace();

}

}

}

}

总结

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

原文链接:https://blog.csdn.net/qq_26562641/article/details/55189875

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 线程池ThreadPoolExecutor使用简介与方法实例 https://www.kuaiidc.com/109604.html

相关文章

发表评论
暂无评论