好得很程序员自学网

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

java多线程教程之如何使用线程池详解

为什么要用 线程池 ?

诸如 web 服务器、数据库服务器、文件服务器或邮件服务器之类的许多服务器应用程序都面临处理来自某些远程来源的大量短小的任务。请求以某种方式到达服务器,这种方式可能是通过网络协议(例如 http、ftp 或 pop)、通过 jms 队列或者可能通过轮询数据库。不管请求如何到达,服务器应用程序中经常出现的情况是:单个任务处理的时间很短而请求的数目却是巨大的。

只有当任务都是同类型并且相互独立时,线程池的性能才能达到最佳。如果将运行时间较长的与运行时间较短的任务混合在一起,那么除非线程池很大,否则将可能造成拥塞,如果提交的任务依赖于其他任务,那么除非线程池无线大,否则将可能造成死锁。

例如饥饿死锁:线程池中的任务需要无限等待一些必须由池中其他任务才能提供的资源或条件。

threadpoolexecutor的通用构造函数:(在调用完构造函数之后可以继续定制threadpoolexecutor)

?

1

2

3

4

5

public threadpoolexecutor( int corepoolsize, int maximumpoolsize, long keepalivetime,

     timeunit unit,blockingqueue<runnable> workqueue,threadfactory threadfactory,

     rejectedexecutionhandler handler){

      //...

}

饱和策略:

threadpoolexecutor允许提供一个blockingqueue来保存等待执行的任务。

当有界队列被填满后,饱和策略开始发挥作用。可以通过调用setrejectedexecutionhandler来修改。

中止是默认的饱和策略,该策略将抛出未检查的rejectedexecutionexception,调用者可以捕获这个异常,然后根据需求编写自己的处理代码。

调用者运行策略实现了一种调节机制,该策略既不会抛弃任务,也不会抛出异常,而是将某些任务回退到调用者,从而降低新任务的流量。

例如对于webserver,当线程池中的所有线程都被占用,并且工作队列被填满后,下一个任务在调用execute时在主线程中执行。

由于执行任务需要一定的时间,因此主线程至少在一段时间内不能提交任何任务,从而使得工作者线程有时间来处理完正在执行的任务。

在这期间,主线程不会调用accept,因此到达的请求将被保存在tcp层的队列中而不是在应用程序的队列中,如果持续过载,那么tcp层最终发现它的请求队列被填满,同样会开始抛弃请求。

因此当服务器过载时,这种过载会逐渐向外蔓延开来---从线程池到工作队列到应用程序再到tcp层,最终到达客户端,导致服务器在高负载下实现一种平缓的性能降低。

?

1

exec.setrejectedexecutionhandler( new threadpoolexecutor.callerrunspolicy());

当工作队列被填满后,没有预定于的饱和策略来阻塞execute。而通过semaphore来现在任务的到达率,可以实现。

?

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

/**

  * 设置信号量的上界设置为线程池的大小加上可排队任务的数量,控制正在执行和等待执行的任务数量。

  */

public class boundedexecutor {

 

  private final executor exec;

  private final semaphore semaphore;

 

  public boundedexecutor(executor exec, int bound){

   this .exec = exec;

   this .semaphore = new semaphore(bound);

  }

 

  public void submittask( final runnable task) throws interruptedexception{

   semaphore.acquire();

   try {

    exec.execute( new runnable(){

     public void run(){

      try {

       task.run();

      } finally {

       semaphore.release();

      }

     }

    });

   } catch (rejectedexecutionexception e){

    semaphore.release();

   }

  }

}

线程工厂

线程池配置信息中可以定制线程工厂,在threadfactory中只定义了一个方法newthread,每当线程池需要创建一个新线程时都会调用这个方法。

?

1

2

3

public interface threadfactory{

  thread newthread(runnable r);

}

?

1

2

3

4

5

6

7

8

9

10

11

12

13

// 示例:将一个特定于线程池的名字传递给mythread的构造函数,从而可以再线程转储和错误日志信息中区分来自不同线程池的线程。

  public class mythreadfactory implements threadfactory{

 

  private final string poolname;

 

  public mythreadfactory(string poolname){

   this .poolname = poolname;

  }

 

  public thread newthread(runnable runnable){

   return new mythread(runnable,poolname);

  }

}

?

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

// 示例:为线程指定名字,设置自定义uncaughtexceptionhandler向logger中写入信息及维护一些统计信息以及在线程被创建或者终止时把调试消息写入日志。

public class mythread extends thread{

  public static final string default_name = "mythread" ;

  private static volatile boolean debuglifecycle = false ;

  private static final atomicinteger created = new atomicinteger();

  private static final atomicinteger alive = new atomicinteger();

  private static final logger log = logger.getanonymouslogger();

 

  public mythread(runnable runnable){

   this (runnable,default_name);

  }

 

  public mythread(runnable runnable, string defaultname) {

   super (runnable,defaultname + "-" + created.incrementandget());

   setuncaughtexceptionhandler( new thread.uncaughtexceptionhandler() {

    @override

    public void uncaughtexception(thread t, throwable e) {

     log.log(level.severe, "uncaught in thread " + t.getname(), e);

 

    }

   });

  }

 

  public void run(){

   boolean debug = debuglifecycle;

   if (debug){

    log.log(level.fine, "created " + getname());

   }

   try {

    alive.incrementandget();

    super .run();

   } finally {

    alive.decrementandget();

    if (debug){

     log.log(level.fine, "exiting " + getname());

    }

   }

 

  }

}

扩展threadpoolexecutor

在线程池完成关闭操作时调用terminated,也就是在所有任务都已经完成并且所有工作者线程也已经关闭后。terminated可以用来释放executor在其生命周期里分配的各种资源,此外还可以执行发送通知、记录日志或者收集finalize统计信息等操作。

示例:给线程池添加统计信息

?

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

/**

  * timingthreadpool中给出了一个自定义的线程池,通过beforeexecute、afterexecute、terminated等方法来添加日志记录和统计信息收集。

  * 为了测量任务的运行时间,beforeexecute必须记录开始时间并把它保存到一个afterexecute可用访问的地方。

  * 因为这些方法将在执行任务的线程中调用,因此beforeexecute可以把值保存到一个threadlocal变量中。然后由afterexecute来取。

  * 在timingthreadpool中使用了两个atomiclong变量,分别用于记录已处理的任务和总的处理时间,并通过包含平均任务时间的日志消息。

  */

public class timingthreadpool extends threadpoolexecutor{

 

  public timingthreadpool( int corepoolsize, int maximumpoolsize,

    long keepalivetime, timeunit unit, blockingqueue<runnable> workqueue) {

   super (corepoolsize, maximumpoolsize, keepalivetime, unit, workqueue);

  }

 

  private final threadlocal< long > starttime = new threadlocal< long >();

  private final logger log = logger.getlogger( "timingthreadpool" );

  private final atomiclong numtasks = new atomiclong();

  private final atomiclong totaltime = new atomiclong();

 

  protected void beforeexecute(thread t,runnable r){

   super .beforeexecute(t, r);

   log.fine(string.format( "thread %s: start %s" , t,r));

   starttime.set(system.nanotime());

  }

 

  protected void afterexecute(throwable t,runnable r){

   try {

    long endtime = system.nanotime();

    long tasktime = endtime - starttime.get();

    numtasks.incrementandget();

    totaltime.addandget(tasktime);

    log.fine(string.format( "thread %s: end %s, time=%dns" , t,r,tasktime));

   } finally {

    super .afterexecute(r, t);

   }

  }

 

  protected void terminated(){

   try {

    log.info(string.format( "terminated: avg time=%dns" , totaltime.get()/numtasks.get()));

   } finally {

    super .terminated();

   }

  }

}

#笔记内容参考  《java并发编程实战》

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

原文链接:https://HdhCmsTestcnblogs测试数据/shanhm1991/p/9899720.html

查看更多关于java多线程教程之如何使用线程池详解的详细内容...

  阅读:14次