如何获取线程的返回值?

获取线程的返回值

  1. 主线程等待法,主线程调用sleep方法(让主线程去循环等待子线程结束并赋值;缺点:代码臃肿,等待时间无法精准控制;不推荐使用);

  2. 使用Thread类的join()阻塞当前线程以等待子线程处理结束(不能精准控制多个线程中的其中一个;不推荐使用);

  3. 通过Callable接口实现call()获取线程返回值(通过FutrueTask Or 线程池获取,推荐使用)

FutrueTask的构造方法可以传入Callable实现类的实例;
isDone()可以判断call是否执行结束;
get()用来获取线程完成后的返回值;

实现

Tips:由于前两种方法都无法精准控制等待时间或者是线程对象,所以对第三种方法进行实现

CallableDemo.java

package Thread;

import java.util.concurrent.Callable;

public class CallableDemo implements Callable<String> {
    @Override
    public String call() throws Exception {
        String res = "Hello";
        System.out.println("Call ready");
        Thread.currentThread().sleep(5000);
        System.out.println("Call down");
        return res;
    }
}

FutureTaskDemo.java(FutrueTask获取线程返回值)

package Thread;


import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class FutureTaskDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask futureTask = new FutureTask(new CallableDemo());
        new Thread(futureTask).start();
        if (!futureTask.isDone()){
            System.out.println("Task is not finshed,Please wait");
        }
        System.out.println("Return value is "+futureTask.get());
    }
}

如何获取线程的返回值?_第1张图片

ThreadPoolDemo.java(线程池获取线程返回值)

package Thread;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadPoolDemo {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<String> future= executorService.submit(new CallableDemo());
        if (!future.isDone()){
            System.out.println("Task is not finshed,Please wait");
        }
        try {
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally {
            executorService.shutdown();
        }
    }
}

如何获取线程的返回值?_第2张图片

你可能感兴趣的:(JAVA基础,多线程,thread,java,future)