获取线程返回值

  1. 通过代码做循环判断
  2. 使用join
  3. 使用Callable接口和FutureTask
  4. 使用线程池

下面通过demo做一下演示

public class MyThreadReturn implements Runnable {
    /** 模拟线程执行完毕后主程序要获取的值*/
    private String returnValue;
    @Override
    public void run() {
        System.out.println("线程执行......");
        /** 模拟IO*/
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程执行完毕......");
        returnValue = "hello world!!!";
    }
    public String getReturnValue(){
        return returnValue;
    }

    public static void main(String[] args) {
        MyThreadReturn myThreadReturn = new MyThreadReturn();
        Thread thread = new Thread(myThreadReturn);
        thread.start();
        System.out.println(myThreadReturn.getReturnValue());
    }
}

以上代码因为MyThreadReturn线程需要5秒执行完毕,主线程中并不能顺利获取到returnValue

null
线程执行..... 

将代码做如下修改

通过循环判断

该方法本质是自己控制业务逻辑

public static void main(String[] args) throws InterruptedException { MyThreadReturn myThreadReturn = new MyThreadReturn(); Thread thread = new Thread(myThreadReturn); thread.start(); /** 通过while循环判断*/ while (myThreadReturn.getReturnValue() == null){ Thread.sleep(1000); } System.out.println(myThreadReturn.getReturnValue()); } 

使用join

使用join方法可以让子线程执行完毕后再执行主线程,本质和通过循环判断一样

public static void main(String[] args) throws InterruptedException {
        MyThreadReturn myThreadReturn = new MyThreadReturn();
        Thread thread = new Thread(myThreadReturn);
        thread.start();
        /** 使用join*/
        thread.join();
        System.out.println(myThreadReturn.getReturnValue());
    }

使用Callable接口和FutureTask

代码如下,通过FutureTask的get()方法获取返回值

public class MyCallable implements Callable<String> {
    @Override
    public String call() throws Exception {
        System.out.println("线程执行......");
        Thread.sleep(5000);
        System.out.println("线程执行完毕......");
        return "hello world!!!";
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
        /***
         * futureTask 实现了 Runnable接口
         * 所以新建线程的时候可以传入futureTask
         * FutureTask重写的run方法中实际是调用了Callable接口在call()方法
         * 所以执行线程的时候回执行call方法的内容
         */
        Thread thread = new Thread(futureTask);
        thread.start();
        String value = futureTask.get();
        System.out.println(value);
    }
}

使用线程池

public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<String> submit = executorService.submit(new MyCallable());
        System.out.println(submit.get());
    }
以上代码返回值均为


线程执行......
线程执行完毕......
hello world!!!



作者:昵称不再更新
链接:https://www.jianshu.com/p/46b26d3d94be
来源:简书

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

猜你喜欢

转载自www.cnblogs.com/-answer/p/12292741.html