ThreadPoolDemo.java 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package course;
  2. import java.util.concurrent.*;
  3. /**
  4. * @author WanJl
  5. * @version 1.0
  6. * @title ThreadPoolDemo
  7. * @description
  8. * @create 2026/8/11
  9. */
  10. public class ThreadPoolDemo {
  11. public static void main(String[] args) {
  12. ThreadPoolExecutor pool=
  13. new ThreadPoolExecutor(2,4,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(2), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
  14. for (int i = 1; i <=8; i++) {
  15. int taskId=i;
  16. try{
  17. pool.execute(()->{
  18. String name = Thread.currentThread().getName();
  19. System.out.println(name+"执行任务"+taskId);
  20. try {
  21. Thread.sleep(2000); //模拟任务耗时,占住线程
  22. } catch (InterruptedException e) {
  23. throw new RuntimeException(e);
  24. }
  25. });
  26. }catch (RejectedExecutionException e){
  27. System.out.println("任务"+ taskId+"被拒绝"+e.getMessage());
  28. }
  29. }
  30. //观察线程池的状态:活动线程数、队列的大小
  31. System.out.println("活动线程数:"+pool.getActiveCount());
  32. System.out.println("队列中任务数:"+pool.getQueue().size());
  33. pool.shutdown(); //关闭线程池
  34. }
  35. }