在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ ExecutorService.invokeAll(超時(shí)了,為什么沒有異常,還正

ExecutorService.invokeAll(超時(shí)了,為什么沒有異常,還正常獲取結(jié)果呢?

最近在學(xué)習(xí)JVM中的并發(fā)庫,concurrent包下的類,demo如下,已經(jīng)超時(shí)了,不知道為什么沒有異常拋出,反而正常獲取到了結(jié)果,按照并發(fā)書中所述,此方法運(yùn)行時(shí)應(yīng)該拋出異常才對,請大家?guī)兔Σ榭匆幌?謝謝!


import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * invokeAll(Collection tasks, long timeout, TimeUnit unit)
 *
 * @author xiaoshu
 */
public class Run {
    public static void main(String[] args) {
        try {
            MyCallableA a = new MyCallableA();
            MyCallableB b = new MyCallableB();

            List<Callable<String>> list = new ArrayList<>();
            list.add(a);
            list.add(b);

            ExecutorService executorService = Executors.newCachedThreadPool();
            System.out.println("X " + LocalDateTime.now());
            List<Future<String>> futures = executorService.invokeAll(list, 2, TimeUnit.SECONDS);
            System.out.println("Y " + LocalDateTime.now());
            for (int i = 0; i < futures.size(); i++) {
                System.out.println(futures.get(i).get());
            }
            System.out.println("Z " + LocalDateTime.now());
        } catch (InterruptedException e) {
            System.out.println("進(jìn)入catch InterruptedException");
            e.printStackTrace();
        } catch (ExecutionException e) {
            System.out.println("進(jìn)入catch ExecutionException");
            e.printStackTrace();
        }
    }
}


class MyCallableB implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("MyCallableB begin " + LocalDateTime.now());
        for (int i = 0; i < 10; i++) {
            Math.random();
            Math.random();
            Math.random();
        }
        System.out.println("MyCallableB end " + LocalDateTime.now());
        return "MyCallableBValue";
    }
}

class MyCallableA implements Callable<String> {
    @Override
    public String call() throws Exception{
        System.out.println("MyCallableA begin " + LocalDateTime.now());
        for (int i = 0; i < 223456666; i++) {
            Math.random();
            Math.random();
            Math.random();
        }
        System.out.println("MyCallableA end " + LocalDateTime.now());
        return "MyCallableAValue";
    }
}

輸出結(jié)果:
clipboard.png

回答
編輯回答
兔囡囡
Executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires, whichever happens first.
鏈接描述

是否超時(shí)應(yīng)該 是以先執(zhí)行的任務(wù)的完成時(shí)間為準(zhǔn)。

2017年4月15日 19:20
編輯回答
心悲涼

會(huì)拋出異常,java.util.concurrent.CancellationException
如果某項(xiàng)值生成任務(wù)(如 FutureTask)的結(jié)果因?yàn)槿蝿?wù)被取消而無法獲取到,則拋出該異常

2018年4月16日 11:19