ThreadPoolDemo03.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package J20250731.demo03_threadPool;
  2. import java.util.concurrent.*;
  3. /**
  4. * @author WanJl
  5. * @version 1.0
  6. * @title ThreadPoolDemo03
  7. * @description
  8. * @create 2025/7/31
  9. */
  10. public class ThreadPoolDemo03 {
  11. public static void main(String[] args) {
  12. /*
  13. 1、核心线程数
  14. 2、最大线程数
  15. 3、空闲线程最大存活时间
  16. 4、时间单位
  17. 5、任务队列
  18. 6、线程工厂
  19. 7、任务拒绝策略
  20. */
  21. ThreadPoolExecutor pool =
  22. new ThreadPoolExecutor(2,
  23. 5,
  24. 2,
  25. TimeUnit.SECONDS, new ArrayBlockingQueue<>(10),
  26. Executors.defaultThreadFactory(),
  27. new ThreadPoolExecutor.AbortPolicy());
  28. for (int i = 0; i < 100; i++) {
  29. try {
  30. pool.submit(() -> {
  31. System.out.println("线程id:" + Thread.currentThread().getId() + ",线程名:" + Thread.currentThread().getName() + "在执行了.....");
  32. try {
  33. Thread.sleep(100);
  34. } catch (InterruptedException e) {
  35. e.printStackTrace();
  36. }
  37. });
  38. } catch (RejectedExecutionException e) {
  39. System.out.println("一桌客人被撵跑了....");
  40. }
  41. }
  42. System.out.println("线程池的线程数:" + pool.getPoolSize());
  43. pool.shutdown();
  44. }
  45. }