Demo05.java 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package J20250801.homework;
  2. import java.util.Random;
  3. import java.util.concurrent.*;
  4. /**
  5. * @author WanJl
  6. * @version 1.0
  7. * @title Demo05
  8. * @description
  9. * @create 2025/8/1
  10. */
  11. public class Demo05 {
  12. private static Random ran=new Random();
  13. public static void main(String[] args) {
  14. ExecutorService pool = Executors.newFixedThreadPool(3);
  15. try{
  16. //提交价格
  17. Future<Integer> priceFuture= pool.submit(() -> getPrice());
  18. //提交库存接口调用任务
  19. Future<Integer> stockFuture=pool.submit(()->getStock());
  20. //提交评价接口调用任务
  21. Future<Integer> commentFuture=pool.submit(()->getCommentCount());
  22. int price=priceFuture.get();
  23. int stock=stockFuture.get();
  24. int comment=commentFuture.get();
  25. System.out.printf("商品信息:价格= %d元,库存= %d件,评价= %d 条好评\n",price,stock,comment);
  26. }catch (Exception e){
  27. System.out.println("接口调用出现异常:"+e.getMessage());
  28. }finally {
  29. //关闭线程池
  30. pool.shutdown();
  31. try {
  32. //等待10秒,10秒后强制关闭
  33. if (!pool.awaitTermination(10, TimeUnit.SECONDS)){
  34. pool.shutdownNow();
  35. }
  36. } catch (InterruptedException e) {
  37. pool.shutdownNow();
  38. }
  39. }
  40. }
  41. public static Integer getPrice() throws InterruptedException {
  42. int processing = processing();
  43. int price=100+ran.nextInt(901);
  44. System.out.println("价格接口调用完成,返回:"+price+"元,耗时"+processing/1000+"秒");
  45. return price;
  46. }
  47. public static Integer getStock() throws InterruptedException {
  48. int processing = processing();
  49. int stock=ran.nextInt(1001);
  50. System.out.println("库存接口调用完成,返回:"+stock+"件,耗时"+processing/1000+"秒");
  51. return stock;
  52. }
  53. public static Integer getCommentCount()throws InterruptedException {
  54. int processing = processing();
  55. int commentCount=ran.nextInt(10001);
  56. System.out.println("评价接口调用完成,返回:"+commentCount+"条好评,耗时"+processing/1000+"秒");
  57. return commentCount;
  58. }
  59. private static int processing() throws InterruptedException {
  60. int i = 1000 + ran.nextInt(2001);
  61. Thread.sleep(i);
  62. return i;
  63. }
  64. }