Future

Future:获得线程执行结果

package mytest;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class FactorialCalculator implements Callable<Integer> {
    private Integer number;

    public FactorialCalculator(int number) {
        this.number = number;
    }

    @Override
    public Integer call() throws Exception {
        int result = 1;
        if ((number == 0) || (number == 1)) {
            result = 1;
        } else {
            for (int i = 2; i < number; i++) {
                result *= i;
                TimeUnit.MILLISECONDS.sleep(20);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
        List<Future<Integer>> resultList = new ArrayList<>();
        Random random = new Random();
        int bound = 10;
        for (int i = 0; i < bound; i++) {
            int number = random.nextInt(10);
            FactorialCalculator factorialCalculator = new FactorialCalculator(number);
            Future<Integer> submit = executor.submit(factorialCalculator);
            resultList.add(submit);// 记录任务对象
        }
        do {
            System.out.println("mai: number of completed tasks:" + executor.getCompletedTaskCount());
            for (int i = 0; i < resultList.size(); i++) {
                Future<Integer> future = resultList.get(i);
                System.out.println("main: ask: " + future.isDone());
            }
            try {
                TimeUnit.MICROSECONDS.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } while (executor.getCompletedTaskCount() < resultList.size());// 直到任务完成

        for (int i = 0; i < resultList.size(); i++) {
            Future<Integer> future = resultList.get(i);// 获取任务结果
            try {
                System.out.println("main: ask number: " + future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}

executor.invokeAny(taskList);
比如taskList中有两个任务
如果两个任务都正常结束,则返回结果是首先完成任务的那个
如果有一个抛了异常,则返回没抛异常的那个
如果都抛异常,那我也抛吧

executor.invokeAll(taskList);实在get的时候抛异常

package mytest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class InvokeAllTest {
    static class Result {
        private String name;
        private int value;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }

    }

    static class Task implements Callable<Result> {
        private String name;

        public Task(String name) {
            this.name = name;
        }

        @Override
        public Result call() throws Exception {
            TimeUnit.SECONDS.sleep(10);
            int value = 0;
            for (int i = 0; i < 5; i++) {
                value += (int) (Math.random() * 100);
            }
            if ("1".equals(name)) {
                throw new RuntimeException();
            }
            Result result = new Result();
            result.setName(name);
            result.setValue(value);
            return result;
        }

    }

    public static void main(String[] args) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

        List<Task> taskList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Task task = new Task(i + "");
            taskList.add(task);
        }
        List<Future<Result>> resultList = null;
        try {
            resultList = executor.invokeAll(taskList);// 等待所有线程执行完毕
        } catch (InterruptedException e) {
            System.out.println("==================");
            e.printStackTrace();
        }
        executor.shutdown();
        for (int i = 0; i < resultList.size(); i++) {
            Future<Result> future = resultList.get(i);
            try {
                Result result = future.get();
                System.out.println(result.getName() + ": " + result.getValue());
            } catch (InterruptedException | ExecutionException e) {
                System.out.println("---------------");
                e.printStackTrace();
            }
        }
    }
}

executor除了submit Callable外,还可以
提交(? extends FutureTask)对象。覆盖FutureTask的done()方法,可以在任务完成后, 进行后续处理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值