Java线程池之创建自定义ThreadFactory

@(高并发)
[TOC]
工厂模式是最常用的模式之一,在创建线程的时候,我们当然也能使用工厂模式来生产Thread,这样就能替代默
认的new THread,而且在自定义工厂里面,我们能创建自定义化的Thread,并且计数,或则限制创建Thread的数量,
给每个Thread设置对应的好听的名字,或则其他的很多很多事情,总之就是很爽,下面我们来展示一个简单的Thread
工厂模式来创建自己的Thread。

  1. package cn.usr.alarm.broadcast.util;
  2. import javafx.concurrent.Task;
  3. import java.util.ArrayList;
  4. import java.util.Date;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.concurrent.ThreadFactory;
  8. /**
  9. * @Package: cn.usr.alarm.broadcast.util
  10. * @Description: TODO
  11. * @author: Rock 【shizhiyuan@usr.cn】
  12. * @Date: 2018/3/19 0019 11:10
  13. */
  14. public class RecorderThreadFactory implements ThreadFactory {
  15. private int counter;
  16. private String name;
  17. private List stats;
  18. public RecorderThreadFactory(String name) {
  19. counter = 0;
  20. this.name = name;
  21. stats = new ArrayList();
  22. }
  23. @Override
  24. public Thread newThread(Runnable run) {
  25. Thread t = new Thread(run, name + "-Thread-" + counter);
  26. counter++;
  27. stats.add(String.format("UsrCloud Alarm thread [%d] with name %s on%s\n" ,t.getId() ,t.getName() ,new Date()));
  28. return t;
  29. }
  30. public String getStas() {
  31. StringBuffer buffer = new StringBuffer();
  32. Iterator it = stats.iterator();
  33. while(it.hasNext()) {
  34. buffer.append(it.next());
  35. buffer.append("\n");
  36. }
  37. return buffer.toString();
  38. }
  39. public static void main(String[] args) {
  40. RecorderThreadFactory factory = new RecorderThreadFactory("MyThreadFactory");
  41. Task task = new Task() {
  42. @Override
  43. protected Object call() throws Exception {
  44. return null;
  45. }
  46. };
  47. Thread thread = null;
  48. for(int i = 0; i < 10; i++) {
  49. thread = factory.newThread(task);
  50. thread.start();
  51. }
  52. System.out.printf("Factory stats:\n");
  53. System.out.printf("%s\n",factory.getStas());
  54. }
  55. }

调用使用:

  1. /**
  2. * 构造一个线程池
  3. */
  4. private static final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
  5. 2,
  6. 4,
  7. 5,
  8. TimeUnit.SECONDS,
  9. new ArrayBlockingQueue<>(200),
  10. new RecorderThreadFactory("WeChat Alarm"),
  11. new ThreadPoolExecutor.DiscardOldestPolicy());