Java ExecutorService示例

在Java中,我们可以使用ExecutorService创建线程池,并使用Future跟踪异步任务的进度。

ExecutorService接受RunnableCallable任务。

  1. 可运行–返回void,不返回任何内容。
  2. 可致电–回报未来。

1. ExecutorService

1.1一个经典的ExecutorService示例创建一个具有5个线程的线程池,提交两个任务,从Future获取结果以及如何处理异常。

ExecutorExample1.java
package com.mkyong.concurrency.executor;

import java.util.concurrent.*;

public class ExecutorExample1 {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(5);

        // Runnable, return void, nothing, submit and run the task async
        executor.submit(() -> System.out.println("I'm Runnable task."));

        // Callable, return a future, submit and run the task async
        Future<Integer> futureTask1 = executor.submit(() -> {
            System.out.println("I'm Callable task.");
            return 1 + 1;
        });

        /* Before Java 8
        executor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("I'm Runnable task.");
            }
        });

        Future<Integer> futureTask1 = executor.submit(new Callable<Integer>() {
            @Override
            public Integer call() {
                System.out.println("I'm Callable task.");
                return 1 + 1;
            }
        });*/

        try {

            otherTask("Before Future Result");

            // block until future returned a result, 
			// timeout if the future takes more than 5 seconds to return the result
            Integer result = futureTask1.get(5, TimeUnit.SECONDS);

            System.out.println("Get future result : " + result);

            otherTask("After Future Result");


        } catch (InterruptedException e) {// thread was interrupted
            e.printStackTrace();
        } catch (ExecutionException e) {// thread threw an exception
            e.printStackTrace();
        } catch (TimeoutException e) {// timeout before the future task is complete
            e.printStackTrace();
        } finally {

            // shut down the executor manually
            executor.shutdown();

        }

    }

    private static void otherTask(String name) {
        System.out.println("I'm other task! " + name);
    }
}

输出量

I'm Runnable task.
I'm Callable task.
I'm other task! Before Future Result
Get future result : 2
I'm other task! After Future Result

2. invokeAll

2.1我们还可以创建一个Callable任务列表,并使用invokeAll运行所有任务

ExecutorExample2.java
package com.mkyong.concurrency.executor;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorExample2 {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newCachedThreadPool();

        List<Callable<Integer>> listOfCallable = Arrays.asList(
                () -> 1,
                () -> 2,
                () -> 3);

        try {

            List<Future<Integer>> futures = executor.invokeAll(listOfCallable);

            int sum = futures.stream().map(f -> {
                try {
                    return f.get();
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }).mapToInt(Integer::intValue).sum();

            System.out.println(sum);

        } catch (InterruptedException e) {// thread was interrupted
            e.printStackTrace();
        } finally {

            // shut down the executor manually
            executor.shutdown();

        }

    }

}

输出量

6

// ...待更新

下载源代码

$ git clone https://github.com/mkyong/java-concurrency.git

参考文献

  1. ExecutorService JavaDoc
  2. 维基百科–线程池

翻译自: https://mkyong.com/java/java-executorservice-examples/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值