【Java多线程】-Callable,Future,FutureTask

一、Callable与Runnable的区别

1)Runnable是一个接口,里面只申明了一个run()方法,run()方法的返回值为void类型,因此,任务执行完后不会返回任何结果。

public interface Runnable {
    public abstract void run();
}

2)Callable也是一个接口,里面也只申明了一个方法call(),该方法的返回值类型为一个泛型,是传递进来的V类型。

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

二、Future

Future可以对具体的Callable任务或者Runnable进取消,查询是否取消,查询是否完成,通过get方法获取返回结果,该方法会阻塞,直到返回结果,Future源码如下:

public interface Future<V> {
    boolean cancel(boolean mayInterruptIfRunning);
    boolean isCancelled();
    boolean isDone();
    V get() throws InterruptedException, ExecutionException;
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

Future+Runnable示例代码:

public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors
                .newSingleThreadScheduledExecutor();
        Future<?> future = executorService.submit(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("睡眠1000毫秒");
            }
        });
        // 取消任务
        future.cancel(true);
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 打印是否取消
        System.out.println(future.isCancelled());
        // 打印是否完成
        System.out.println(future.isDone());

    }

Future+Callable示例代码:


        ScheduledExecutorService executorService = Executors
                .newSingleThreadScheduledExecutor();
        Future<String> future = executorService.submit(new Callable<String>() {

            @Override
            public String call() throws Exception {
                return "Hello tailyou!";
            }
        });
        // 取消任务
        // future.cancel(true);
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        // 打印是否取消
        System.out.println(future.isCancelled());
        // 打印是否完成
        System.out.println(future.isDone());

三、FutureTask

先看看FutureTask的源码:

public class FutureTask<V> implements RunnableFuture<V>

FutureTask实现了RunnableFuture,那么RunnableFuture又是什么玩意呢?再看看RunnableFuture的源码:

public interface RunnableFuture<V> extends Runnable, Future<V> {
    void run();
}

RunnableFuture继承了Runnable接口和Future接口,因此它既可以作为Runnable被线程执行,又可以作为Future得到Callable的返回值。FutureTask是Future的唯一实现类;
示例代码:

ScheduledExecutorService executorService = Executors
                .newSingleThreadScheduledExecutor();
        FutureTask<String> futureTask = new FutureTask<>(
                new Callable<String>() {

                    @Override
                    public String call() throws Exception {
                        return "Hello tailyou!";
                    }
                });
        executorService.submit(futureTask);
        try {
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值