Several ways to get thread return value in java

In my previous work, I mainly wrote business codes. Threads were rarely used, and I didn’t consider how to get the return value after executing the thread. However, the run() method in the thread has no return value. So what should I do if I want to get the corresponding value after the thread is executed? Summarize with recent study. There are several ways to return values ​​from threads.

Table of contents

1. Take the value directly

2. Judging by loop

3. Use join

4. Use Callable interface and FutureTask

5. Use thread pool


1. Take the value directly

Let's do a demonstration through 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());
    }
}

Because the above code takes 5 seconds to execute for the MyThreadReturn thread, the returnValue cannot be successfully obtained in the main thread

null
线程执行.....

Modify the code as follows

2. Judging by loop

The essence of this method is to control the business logic by yourself

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());
    }

3. Use join

Using the join method allows the sub-thread to execute the main thread after execution, which is essentially the same as judging through the loop

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());
    }

4. Use Callable interface and FutureTask

The code is as follows, get the return value through the get() method of FutureTask

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);
    }
}

5. Use thread pool

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());
    }

The return value of the above code is

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

Several ways to get thread return value in java - Programmer Sought

Guess you like

Origin blog.csdn.net/Goals1989/article/details/128718484