Java多线程 Future与Callable

概述

  1. Runnable的缺陷
  2. Callable接口
  3. Future类
  4. 用法1:线程池的submit方法返回Future对象
  5. 用法2:用FutureTask来创建Future
  6. Future注意点

Runnable的缺陷

  1. 没有返回值
  2. 无法抛出check exception。

为什么有这样的缺陷:

Callable接口

类似于Runnable,被其他线程执行的任务,重写call()方法。返回一个泛型返回值,可以抛出异常。

Future类

Future作用,用子线程去执行耗时的计算,计算完成后取回结果。

Callable和Future的关系

我们可以用Future.get()来获取Callable接口返回执行结果,还可以通过Future.isDone()来判断任务是否已经执行完了,以及取消这个任务,显示获取任务的结果等。
call()未执行完毕之前,调用get()线程(假定此时是主线程)会被阻塞,直到call()方法返回了结果后,此时future.get()才会得到该结果,然后主线程才会切换到runnable状态。
所以Future是一个存储器,它存储了call()这个任务的结果,而这个任务的执行时间是无法提前确定的,因为这完全取决于call()方法执行的情况.

Future的主要方法

  1. get方法的行为取决于Callable任务的状态,只有以下5种情况
    1. 任务正常完成:get()方法会立刻返回结果
    2. 任务尚未完成(任务还没开始或在进行中):get()将阻塞并直到任务完成。
    3. 任务执行过程中抛出Exception:get()方法会抛出ExecutionException:这里抛出异常,是call()执行时产生的那个异常,这个异常的类型是java.util.concurrent.ExecutionException。不论call()执行时抛出的异常类型是什么,最后get()方法抛出的异常类型都是ExecutionException。
    4. 任务被取消:get()方法会抛出CancellationException。
    5. 任务超时:get()方法有一个重载方法,是传入一个延迟时间的,如果时间到了还没有获得结果,get方法就会抛出TimeoutException。
  2. get(long timeout,TimeUnit unit):有超时的获取
    1. 如果call()在规定时间内完成了任务,那么就会正常获取到返回值;如果在指定时间内没有计算出结果,那么就会抛出TimeoutException
    2. 超时不获取,任务需取消。
  3. idDone()方法:判断线程是否执行完毕
  4. isCanceled()方法:判断是否被取消
  5. cancel()
public class MultiFutures {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(20);
        ArrayList<Future> futures = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            Future<Integer> future = service.submit(new CallableTask());
            futures.add(future);
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < 20; i++) {
            Future<Integer> future = futures.get(i);
            try {
                Integer a = future.get();
                System.out.println(a);
            } 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();
        }
    }
}
public class GetException {
    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(20);
        Future<Integer> future = service.submit(new CallableTask());
        try {
            Thread.sleep(1000);
            System.out.println(future.isDone());
            future.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    static class CallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            throw new IllegalArgumentException("Callable抛出异常");
        }
    }
}
public class TimeOut {
    private static final Ad DEFAULT_AD = new Ad("默认广告");
    private 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);
                //return new Ad("正常广告");
            } catch (InterruptedException e){
                System.out.println("sleep期间被中断了");
            }
            return new Ad("正常广告");
        }
    }
    public void printAd(){
        Future<Ad> f = exec.submit(new FetchAdTask());
        Ad ad = null;
        try {
            ad = f.get(5000, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            ad = new Ad("默认广告");
            System.out.println("超时");
            f.cancel(false);
        }
        System.out.println(ad);
    }
    public static void main(String[] args) {
        TimeOut timeOut = new TimeOut();
        timeOut.printAd();
    }
}

cancel 方法

  1. 如果这个任务还没有开始执行,那么这种情况最简单,任务会被正常的取消,未来也不会被执行,方法返回true。
  2. 如果任务已完成,或者已取消:那么cancel方法会被执行失败,方法返回false;
  3. 如果这个任务已经开始执行了,那么这个取消方法将不会直接取消该任务,而是会根据我们填的参数做判断。

用FutureTask来创建Future

在这里插入图片描述

用FutureTask来获取Future和任务的结果。把Callable实例当作参数,生成FutureTask的对象,然后把这个对象当作一个Runnable对象,用线程池或另起线程去执行这个Runnable对象,最后通过FutureTask获取刚才执行的结果。
演示FutureTask的用法

public class FutureTaskDemo {
    public static void main(String[] args) {
        Task task = new Task();
        FutureTask<Integer> integerFutureTask = new FutureTask<>(task);
        ExecutorService service = Executors.newCachedThreadPool();
        service.submit(integerFutureTask);
        //new Thread(integerFutureTask).start();
        try {
            System.out.println(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);
        return 0;
    }
}

Future的注意点

  • 当for循环批量获取future的结果时,容易发生一部分线程很慢的情况,get方法调用时应使用timeout限制。
  • Future的生命周期不能后退
    • 生命周期只能前进,不能后退。就和线程池的生命周期一样,一旦完全完成了任务,他就永久停在了已完成的状态,不能冲头再开。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值