【Beautiful JUC Part.11】Future和Callable治理线程

【Beautiful JUC Part.11】Future和Callable治理线程

一、为什么需要Future和Callable

1、Runnable的缺陷

线程没有返回值

image-20220212203327496

run方法无法抛出checked Exception

image-20220212203855777

这是因为run()方法在声明的时候就规定好了形式。只能通过try/catch捕获。

2、Callable接口

类似于Runnable,被其他线程执行的任务

实现call方法

有返回值

image-20220212204144497

3、Future类

作用:一个方法的计算可能会很耗时,这个时候,在计算的过程中,没有必要在原地等待计算完毕返回,这也会浪费自己的时间,这不是明智的选择。如果遇到耗时的方法,使用子线程去执行,子线程执行的时候,我可以去做其他的事情,到了想获取结果的时候,通过Future去获取子线程的结果。

4、Callable和Future的关系

image-20220212204540032

二、Future的主要方法:一共五个

1、get()方法:获取结果

get方法的行为取决于Callable任务的状态,只有以下这5种情况:

  • 任务正常完成:get方法会立刻返回结果
  • 任务尚未完成(任务还没开始或者进行中):get将阻塞并直到任务完成

异常的情况:

image-20220212205232174

2、get(long timeout, TimeUtil unit):有超时的获取

image-20220212205332467

3、cancel()方法

取消任务的执行

4、isDone()方法

判断线程是否执行完毕,并不代表任务是成功的执行了,异常和中断也算是执行完毕了。

5、isCancelled()方法

判断是否被取消

三、Future代码演示

1、用法一:线程池的submit方法返回Future对象

image-20220212205634727

image-20220212210509876

import java.util.Random;
import java.util.concurrent.*;

/**
 *描述:演示一个Future的使用方法
 */
public class OneFuture {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(10);
        Future<Integer> future = service.submit(new CallableTask());
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        service.shutdown();
    }

    static class CallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            Thread.sleep(3000);
            return new Random().nextInt();
        }
    }
}

2、用法二:多个任务,用Future数组来获取结果

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;

/**
 * 描述:演示批量提交任务时,用List来批量接收结果
 */
public class MultiFutures {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);
        ArrayList<Future> futures = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            Future<Integer> future = service.submit(new CallableTask());
            futures.add(future);
        }

        for (int i = 0; i < 20; i++) {
            Future<Integer> future = futures.get(i);
            try {
                Integer integer = future.get();
                System.out.println(integer);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
    }

    static class CallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            Thread.sleep(3000);
            return new Random().nextInt();
        }
    }
}

3、任务执行过程中抛出Exception和isDone展示

抛出ExecutionException

import java.util.concurrent.*;

/**
 * 描述:演示get方法过程中抛出异常,for循环为了演示抛出Exception的时机:
 * 并不是说一产生异常就抛出,直到我们get执行时,才会抛出。
 */
public class GetException {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(2);
        Future<Integer> future = service.submit(new CallableTask());
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println(i);
                Thread.sleep(500);
            }
            System.out.println(future.isDone());
            future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
            System.out.println("InterruptedException异常");
        } catch (ExecutionException e) {
            e.printStackTrace();
            System.out.println("ExecutionException异常");
        }
    }

    static class CallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            throw new IllegalArgumentException("Callable抛出异常");
        }
    }
}

任务在submit的时候就已经开始执行了,异常已经抛出了,但是只有当get()的时候才会感知。

调用future.isDone()可以看出已经结束。

4、演示get超时方法

需要注意超时后需要处理,调用future.cancel(),演示传入cancel传入true和false的区别,代表是否中断正在执行的任务。

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * 描述:     演示get的超时方法,需要注意超时后处理,调用future.cancel()。演示cancel传入true和false的区别,代表是否中断正在执行的任务。
 */
public class Timeout {

    private static final Ad DEFAULT_AD = new Ad("无网络时候的默认广告");
    private static final ExecutorService exec = Executors.newFixedThreadPool(10);

    static class Ad {

        String name;

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

        @Override
        public String toString() {
            return "Ad{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }


    static class FetchAdTask implements Callable<Ad> {

        @Override
        public Ad call() throws Exception {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                System.out.println("sleep期间被中断了");
                return new Ad("被中断时候的默认广告");
            }
            return new Ad("旅游订票哪家强?找某程");
        }
    }


    public void printAd() {
        Future<Ad> f = exec.submit(new FetchAdTask());
        Ad ad;
        try {
            ad = f.get(2000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            ad = new Ad("被中断时候的默认广告");
        } catch (ExecutionException e) {
            ad = new Ad("异常时候的默认广告");
        } catch (TimeoutException e) {
            ad = new Ad("超时时候的默认广告");
            System.out.println("超时,未获取到广告");
            boolean cancel = f.cancel(true);
            System.out.println("cancel的结果:" + cancel);
        }
        exec.shutdown();
        System.out.println(ad);
    }

    public static void main(String[] args) {
        Timeout timeout = new Timeout();
        timeout.printAd();
    }
}

5、cancel方法:取消任务的执行

image-20220212214500857

传入true与false的时机

image-20220212214618699

6、用法三:用FutureTask来获取Future和任务的结果

FutureTask是一种包装器,可以把Callable转化成Future和Runnable,它同时实现二者的接口。

image-20220212214757656

所以它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。

image-20220212214845524

代码演示

import java.util.concurrent.*;

/**
 * 描述:演示FutureTask的用法
 */
public class FutureTaskDemo {
    public static void main(String[] args) {
        Task task = new Task();
        FutureTask<Integer> integerFutureTask = new FutureTask<>(task);
        //new Thread(integerFutureTask).start();

        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(integerFutureTask);
        try {
            System.out.println("task运行结果: " + integerFutureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
class Task implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        System.out.println("子线程正在计算");
        Thread.sleep(3000);
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum += i;
        }
        return sum;
    }
}

7、Future的注意点

当for循环批量获取future的结果时,容易发生一部分线程很慢的情况,get方法调用时应使用timeout限制

image-20220212215442976

Future的生命周期不能后退

image-20220212215819544

posted @ 2022-02-12 21:59  DarkerG  阅读(38)  评论(0编辑  收藏  举报