java

java多线程解析之Callable

2021-12-12  本文已影响0人  java自力更生

Callable和Runnable有什么区别?

首先,Runnable是出自jdk1.0,Callable出自jdk1.5,那么,后出的类肯定对于前者有增强。
再看Runnable的run方法与Callable的call方法进行对比

// Runnable
public abstract void run();

// Callable
V call() throws Exception;

可以看出,run方法没有返回值,call方法有返回值并能够抛出异常。

在对Callable原理进行解析之前,首先先看一下Callable的基本用法

方式一:通过FutureTask,交给线程池执行,阻塞等待结果返回

    public static void main(String[] args) throws Exception {
        FutureTask<String> futureTask = new FutureTask<String>(new Callable<String>() {
            public String call() throws InterruptedException {
                Thread.sleep(3000L);
                System.out.println("当前线程:" + Thread.currentThread().getName());
                return "hello world";
            }
        });
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        System.out.println("开始时间戳为:" + System.currentTimeMillis());
        executorService.submit(futureTask);
        String result = futureTask.get();
        System.out.println("结束时间戳为:" + System.currentTimeMillis() + ",result = " + result);
    }
结果打印:
开始时间戳为:1639275517192
当前线程:pool-1-thread-1
结束时间戳为:1639275520202,result = hello world

可以看出,callable的逻辑是在异步线程中处理的,并且,主线程通过阻塞式接受异步线程返回的内容。
那么,如果直接调用futureTask的run方法会怎样?

    public static void main(String[] args) throws Exception {
        FutureTask<String> futureTask = new FutureTask<String>(new Callable<String>() {
            public String call() throws InterruptedException {
                Thread.sleep(3000L);
                System.out.println("当前线程:" + Thread.currentThread().getName());
                return "hello world";
            }
        });
        System.out.println("开始时间戳为:" + System.currentTimeMillis());
        futureTask.run();
        String result = futureTask.get();
        System.out.println("结束时间戳为:" + System.currentTimeMillis() + ",result = " + result);
    }
结果打印:
开始时间戳为:1639275759794
当前线程:main
结束时间戳为:1639275762796,result = hello world

结果和直接调用Runnable的方法是一样的,最终是由主线程完成执行

方式二:通过线程池执行,返回Future对象

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        System.out.println("开始时间戳为:" + System.currentTimeMillis());
        Future<String> future = executorService.submit(new Callable<String>() {
            public String call() throws InterruptedException {
                Thread.sleep(3000L);
                System.out.println("当前线程:" + Thread.currentThread().getName());
                return "hello world";
            }
        });
        String result = future.get();
        System.out.println("结束时间戳为:" + System.currentTimeMillis() + ",result = " + result);
    }
结果打印:
开始时间戳为:1639276055569
当前线程:pool-1-thread-1
结束时间戳为:1639276058583,result = hello world

实现效果与方式一相同,这里返回的Future,实际上也是FutureTask


原理分析

首先分析下线程池的submit方法

    // FutureTask传入方式调用的submit方法
    public Future<?> submit(Runnable task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<Void> ftask = newTaskFor(task, null);
        execute(ftask);
        return ftask;
    }

    // Callable传入方式调用的submit方法
    public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        RunnableFuture<T> ftask = newTaskFor(task);
        execute(ftask);
        return ftask;
    }

1.最终都会调用newTaskFor方法生成一个RunnableFuture方法
2.调用execute方法
3.返回RunnableFuture对象
线程池相关的原理不在本文章中具体展开,有兴趣的小伙伴可以自行研究或者在之后的文章中推出详解

再分析下future.get方法如何阻塞等待异步线程执行结果

    public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            // 如果状态还在进行中,或者刚创建,就阻塞等待
            s = awaitDone(false, 0L);
        // 调用Report,返回结果或者抛出异常
        return report(s);
    }

    private V report(int s) throws ExecutionException {
        Object x = outcome;
        if (s == NORMAL)
            // 状态正常,返回结果
            return (V)x;
        if (s >= CANCELLED)
            // 状态取消,抛出取消异常
            throw new CancellationException();
        // 抛出程序执行异常
        throw new ExecutionException((Throwable)x);
    }

FutureTask内部维护了任务进行的状态,当异步任务完成时,会将状态码设置为已完成,如果发生异常,会将状态码设置成对应的异常状态码。

如何自己实现一个类似的能够有返回值的Runnable

    public static class MyRunnable implements Runnable {

        private String result;

        private AtomicBoolean finished = new AtomicBoolean();

        public void run() {
            try {
                Thread.sleep(3000L);
                System.out.println("当前线程:" + Thread.currentThread().getName());
                this.result = "hello world";
                finished.compareAndSet(false, true);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public String get() {
            while (true) {
                if (finished.get()) {
                    return result;
                }
            }
        }

    }

    public static void main(String[] args) throws Exception {
        System.out.println("开始时间戳为:" + System.currentTimeMillis());
        MyRunnable myRunnable = new MyRunnable();
        new Thread(myRunnable).start();
        String result = myRunnable.get();
        System.out.println("结束时间戳为:" + System.currentTimeMillis() + ",result = " + result);
    }
结果打印:
开始时间戳为:1639280212975
当前线程:异步线程
结束时间戳为:1639280215984,result = hello world

本质上就是调用线程持有了异步线程的对象引用,jdk给我们封装好了对应的逻辑,无须额外处理。

上一篇 下一篇

猜你喜欢

热点阅读