1. package concurrent;
    2. import java.util.concurrent.*;
    3. public class C02_ExThreadpool {
    4. public static class MyTask implements Runnable{
    5. private String name;
    6. public MyTask(String name){ this.name = name; }
    7. public String getName() { return name; }
    8. @Override
    9. public void run() {
    10. System.out.println(Thread.currentThread().getId() + ":" + name);
    11. try{ Thread.sleep(1000);}
    12. catch (InterruptedException e) { e.printStackTrace(); }
    13. }
    14. }
    15. /**
    16. * .通过自定义的线程工厂可以自定义线程的状态等信息
    17. */
    18. public static class MyThreadFactory implements ThreadFactory{
    19. @Override
    20. public Thread newThread(Runnable r) {
    21. Thread t = new Thread(r);
    22. // t.setDaemon(true); //设置为守护线程,主线程退出后自动销毁
    23. System.out.println("create " + t);
    24. return t;
    25. }
    26. }
    27. public static void main(String[] args) throws InterruptedException{
    28. /*
    29. *.创建线程池,并重写线程池的beforeExecute、afterExecute、terminated。
    30. *.这三个方法默认时空的,但我们可以重写去做一些事情
    31. */
    32. ExecutorService es = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MICROSECONDS,
    33. new LinkedBlockingDeque<>(), new MyThreadFactory()) {
    34. @Override
    35. protected void beforeExecute(Thread t, Runnable r) {
    36. System.out.println("准备执行:" + ((MyTask)r).getName());
    37. }
    38. @Override
    39. protected void afterExecute(Runnable r, Throwable t) {
    40. System.out.println("执行完成:" + ((MyTask)r).getName());
    41. }
    42. @Override
    43. protected void terminated() {
    44. System.out.println("线程池退出");
    45. }
    46. };
    47. //添加任务
    48. for(int i=0 ; i<3 ; i++){
    49. es.execute(new MyTask("Task-" + i));
    50. Thread.sleep(10);
    51. }
    52. es.shutdown(); //发送一个信号给线程池,线程池在完成当前所有任务后关闭
    53. }
    54. }

    console

    1. create Thread[Thread-0,5,main]
    2. 准备执行:Task-0
    3. 11:Task-0
    4. create Thread[Thread-1,5,main]
    5. 准备执行:Task-1
    6. 12:Task-1
    7. create Thread[Thread-2,5,main]
    8. 准备执行:Task-2
    9. 13:Task-2
    10. 执行完成:Task-0
    11. 执行完成:Task-1
    12. 执行完成:Task-2
    13. 线程池退出