问题:如何给ExecutorService分配任务

2019-01-22  本文已影响6人  Dream_Lin

问题

如何给ExecutorService分配任务

答案

给ExecutorService分配任务

ExecuteService可以执行Runnable任务,也可以执行Callable任务.ExecutorService有很多方法可以执行任务,包括execute()(从Executor接口继承),还有submit(),invokeAny(),invokeAll().

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Runnable runnableTask = () -> {
            System.out.println("run task");
        };

        Callable<String> callableTask = () -> {
            System.out.println("callable task");
            return "callable task return value";
        };
        List<Callable<String>> callableTasks = new ArrayList<>();
        callableTasks.add(callableTask);
        callableTasks.add(callableTask);
        callableTasks.add(callableTask);

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        //execute()方法
        executorService.execute(runnableTask);

        //submit()方法
        Future<String> future = executorService.submit(callableTask);
        System.out.println("submit result:" + future.get());

        //invokeAny()方法
        String invokeAnyResult = null;
        try {
            invokeAnyResult = executorService.invokeAny(callableTasks);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("invokeAny result:" + invokeAnyResult);

        //invokeAll()方法
        List<Future<String>> invokeAllResultList = Arrays.asList();
        try {
            invokeAllResultList = executorService.invokeAll(callableTasks);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < invokeAllResultList.size(); i++) {
            System.out.println("invokeAllResult" + " " + i + ":" + invokeAllResultList.get(i).get());
        }


    }
}

executorService.execute(runnableTask);
 Future<String> future = executorService.submit(callableTask);
 System.out.println("submit result:" + future.get());
        String invokeAnyResult = null;
        try {
            invokeAnyResult = executorService.invokeAny(callableTasks);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("invokeAny result:" + invokeAnyResult);

 List<Future<String>> invokeAllResultList = Arrays.asList();
        try {
            invokeAllResultList = executorService.invokeAll(callableTasks);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < invokeAllResultList.size(); i++) {
            System.out.println("invokeAllResult" + " " + i + ":" + invokeAllResultList.get(i).get());
        }
上一篇 下一篇

猜你喜欢

热点阅读