1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package J20250801.homework;
- import java.util.Random;
- import java.util.concurrent.*;
- /**
- * @author WanJl
- * @version 1.0
- * @title Demo05
- * @description
- * @create 2025/8/1
- */
- public class Demo05 {
- private static Random ran=new Random();
- public static void main(String[] args) {
- ExecutorService pool = Executors.newFixedThreadPool(3);
- try{
- //提交价格
- Future<Integer> priceFuture= pool.submit(() -> getPrice());
- //提交库存接口调用任务
- Future<Integer> stockFuture=pool.submit(()->getStock());
- //提交评价接口调用任务
- Future<Integer> commentFuture=pool.submit(()->getCommentCount());
- int price=priceFuture.get();
- int stock=stockFuture.get();
- int comment=commentFuture.get();
- System.out.printf("商品信息:价格= %d元,库存= %d件,评价= %d 条好评\n",price,stock,comment);
- }catch (Exception e){
- System.out.println("接口调用出现异常:"+e.getMessage());
- }finally {
- //关闭线程池
- pool.shutdown();
- try {
- //等待10秒,10秒后强制关闭
- if (!pool.awaitTermination(10, TimeUnit.SECONDS)){
- pool.shutdownNow();
- }
- } catch (InterruptedException e) {
- pool.shutdownNow();
- }
- }
- }
- public static Integer getPrice() throws InterruptedException {
- int processing = processing();
- int price=100+ran.nextInt(901);
- System.out.println("价格接口调用完成,返回:"+price+"元,耗时"+processing/1000+"秒");
- return price;
- }
- public static Integer getStock() throws InterruptedException {
- int processing = processing();
- int stock=ran.nextInt(1001);
- System.out.println("库存接口调用完成,返回:"+stock+"件,耗时"+processing/1000+"秒");
- return stock;
- }
- public static Integer getCommentCount()throws InterruptedException {
- int processing = processing();
- int commentCount=ran.nextInt(10001);
- System.out.println("评价接口调用完成,返回:"+commentCount+"条好评,耗时"+processing/1000+"秒");
- return commentCount;
- }
- private static int processing() throws InterruptedException {
- int i = 1000 + ran.nextInt(2001);
- Thread.sleep(i);
- return i;
- }
- }
|