卖酒人 2021-08-30 19:15 采纳率: 0%
浏览 80
已结题

关于futuretask执行任务超时测试结果不正确的问题,请问如下代码为什么部分本该正常执行的结果超时了



```java
@Test
    public void test() {
        Thread thread1 = new Thread(new Thread1());
        Thread thread2 = new Thread(new Thread2());
        try {
            thread1.start();
            thread2.start();
            Thread.sleep(30000);
            thread1.interrupt();
            thread2.interrupt();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



    class Thread1 implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                aa(22);
            }
        }
    }

    class Thread2 implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                aa(103);
            }
        }
    }

    public  void aa(int a) {

        Future<Integer> future = executorService.submit(new test(a));
        try {
            Integer result = future.get(5, TimeUnit.MILLISECONDS);
            System.out.println("任务正常," + result);
        } catch (InterruptedException | ExecutionException e) {
            System.out.println("aaaa");
        }catch (TimeoutException e){
            future.cancel(true);
            if (a==22){
                System.out.println("任务超时"+a);
            }


            //future.cancel(true);
        }
    }

    class test implements Callable<Integer>{

        private int a;

        public test(int a) {
            this.a = a;
        }

        @Override
        public Integer call() {
            long time = System.currentTimeMillis();
            while (!Thread.interrupted()){
                if (a > 100) {
                    while (!Thread.currentThread().isInterrupted()){
                        for (int i=0;i<Integer.MAX_VALUE;i++){
                            new Integer(0);
                        }
                    }

                }
                if (a < 100) {
                    System.out.println("耗时2。。。。。。"+(System.currentTimeMillis()-time));
                   return a;
                }
            }
            System.out.println("耗时。。。。。。"+(System.currentTimeMillis()-time));

            throw new RuntimeException();
        }
    }

```

  • 写回答

1条回答 默认 最新

  • 有问必答小助手 2021-09-01 10:10
    关注

    你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答


    本次提问扣除的有问必答次数,将会以问答VIP体验卡(1次有问必答机会、商城购买实体图书享受95折优惠)的形式为您补发到账户。


    因为有问必答VIP体验卡有效期仅有1天,您在需要使用的时候【私信】联系我,我会为您补发。

    评论

报告相同问题?

问题事件

  • 系统已结题 9月7日
  • 修改了问题 8月30日
  • 创建了问题 8月30日

悬赏问题

  • ¥15 通联支付网上收银统一下单接口
  • ¥15 angular有偿编写,
  • ¥15 centos7系统下abinit安装时make出错
  • ¥15 hbuildex运行微信小程序报错
  • ¥15 关于#python#的问题:我知道这个问题对你们来说肯定so easy
  • ¥15 wpf datagrid如何实现多层表头
  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错