FutureTask取结果超时代码小测试

public static void main(String[] args) throws TimeoutException{
            Callable<Integer> callable1 = new Callable<Integer>() {
                public Integer call() throws Exception {
                    Thread.sleep(5000); -- 故意执行五秒
                    return new Random().nextInt(100);
                }
            };
            Callable<Integer> callable2 = new Callable<Integer>() {
                public Integer call() throws Exception {
                    return new Random().nextInt(100);
                }
            };
            FutureTask<Integer> future1 = new FutureTask<Integer>(callable1);
            FutureTask<Integer> future2 = new FutureTask<Integer>(callable2);
            
//            new Thread(future1).start();
            ExecutorService service = Executors.newFixedThreadPool(3);
            service.submit(future1);
            service.submit(future2);
            try {
//                Thread.sleep(1000);// 可能做一些事情
                try
                {
                    System.out.println(future1.get(4000,TimeUnit.MILLISECONDS)); -- 4秒超时
                    
                }
                catch (TimeoutException e)
                {
                    System.out.println("time out");
                }
                System.out.println(future2.get(4000,TimeUnit.MILLISECONDS));
                
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

执行结果

time out
25

结论:

1  future1.get 会阻塞 future2.get由于在后面所以不会执行

2  future1.get发生了超时,此时至少已经等待了4秒了。但是future2.get是可以正常返回的,说明超时时间是call方法中执行的时间。

另外的小发现,try 块中如果第一句发生了异常,那么try 块中剩余语句均不执行。java都搞了3年多了,才意识到这个知识点,真是惭愧。

 
原文地址:https://www.cnblogs.com/juniorMa/p/5851789.html