Java之ExecutorService示例分享

乔欣 Java经验 发布时间:2023-01-31 15:34:35 阅读数:9406 1
下文笔者讲述java代码之ExecutorService的使用方法,如下所示

ExecutorService功能

ExecutorService的功能:
    用于创建线程池
    并使用Future跟踪异步任务的进度

注意事项:
    ExecutorService可接受
	   Runnable和Callable任务    

ExecutorService示例1

package com.java265.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

invokeAll

创建一个Callable任务列表
并使用invokeAll运行所有任务
package com.java265.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();
        }
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202301/16751505355592.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者