卖酒人 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日

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名