Demo08.java 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package J20250801.homework;
  2. import java.util.concurrent.Executors;
  3. import java.util.concurrent.LinkedBlockingQueue;
  4. import java.util.concurrent.ThreadPoolExecutor;
  5. import java.util.concurrent.TimeUnit;
  6. /**
  7. * @author WanJl
  8. * @version 1.0
  9. * @title Demo08
  10. * @description
  11. * @create 2025/8/1
  12. */
  13. public class Demo08 {
  14. private static int successCount=0; //这个值是有问题的
  15. private static int errorCount=0;
  16. public static void main(String[] args) {
  17. ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
  18. 10,
  19. 20,
  20. 30,
  21. TimeUnit.SECONDS,
  22. new LinkedBlockingQueue<>(1000),
  23. Executors.defaultThreadFactory(),
  24. new ThreadPoolExecutor.AbortPolicy()
  25. );
  26. long start = System.currentTimeMillis();
  27. for (int i = 0; i < 1000; i++) {
  28. int x=i+1;
  29. poolExecutor.submit(()->{
  30. try {
  31. Thread.sleep(500); //每条模拟耗时5ms
  32. successCount+=100; //成功1次
  33. } catch (InterruptedException e) {
  34. errorCount+=100;
  35. }
  36. System.out.println("批次["+x+"]导入完成,成功["+successCount+"]条");
  37. System.out.println("批次["+x+"]导入被中断,失败["+errorCount+"]条");
  38. });
  39. }
  40. poolExecutor.shutdown();
  41. try {
  42. if (!poolExecutor.awaitTermination(10,TimeUnit.MICROSECONDS)){
  43. poolExecutor.shutdownNow();
  44. }
  45. } catch (InterruptedException e) {
  46. poolExecutor.shutdownNow();
  47. }
  48. long end = System.currentTimeMillis();
  49. long time=end-start;
  50. System.out.println("总耗时:"+time+"毫秒");
  51. System.out.println("成功["+successCount+"]条");
  52. System.out.println("失败["+errorCount+"]条");
  53. }
  54. }