ThreadPoolDemo04.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package J20250731.demo03_threadPool;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.concurrent.*;
  5. /**
  6. * @author WanJl
  7. * @version 1.0
  8. * @title ThreadPoolDemo04
  9. * @description
  10. * @create 2025/7/31
  11. */
  12. public class ThreadPoolDemo04 {
  13. public static void main(String[] args) {
  14. ArrayList<Student> list = new ArrayList<>();
  15. for (int i = 0; i < 2000000; i++) {
  16. int age = (int) (Math.random() * 100);
  17. int n = i + 1;
  18. Student s = new Student(n, "学生" + n, age, age % 2 == 0 ? "男" : "女");
  19. list.add(s);
  20. }
  21. ThreadPoolExecutor pool = new ThreadPoolExecutor(
  22. 2,
  23. 5,
  24. 20,
  25. TimeUnit.MICROSECONDS,
  26. new ArrayBlockingQueue<>(10),
  27. Executors.defaultThreadFactory(),
  28. new ThreadPoolExecutor.AbortPolicy());
  29. long start = System.currentTimeMillis();
  30. pool.submit(() -> {
  31. //获取每个6年龄的学生有多少位(需要用到HashMap)
  32. HashMap<Integer, Integer> map1 = new HashMap<>();
  33. for (Student s : list) {
  34. Integer age1 = s.getAge();
  35. map1.put(age1, map1.getOrDefault(age1, 0) + 1);
  36. }
  37. System.out.println("每个年龄的学生数量是:" + map1);
  38. });
  39. pool.submit(() -> {
  40. //获取男生多少位,女生多少位
  41. HashMap<String, Integer> map2 = new HashMap<>();
  42. for (Student s : list) {
  43. String sex = s.getSex();
  44. map2.put(sex, map2.getOrDefault(sex, 0) + 1);
  45. }
  46. System.out.println("男女生数量分别是是:" + map2);
  47. });
  48. pool.shutdown();
  49. long end = System.currentTimeMillis();
  50. System.out.println("程序执行总耗时:" + (end - start) + "毫秒");
  51. }
  52. }