Several ways to get Java thread return value

In the actual development process, we sometimes encounter that the main thread calls the sub thread, and we have to wait for the result returned by the sub thread to carry out the business of the next action.

So how to get the value returned by the sub thread? I have summarized three ways:

  1. The main thread waits.
  2. The Join method waits.
  3. Implement the Callable interface.

Entity class

 1 package com.basic.thread;
 2 
 3 /**
 4  * @author zhangxingrui
 5  * @create 2019-02-17 22:14
 6  **/
 7 public class Entity {
 8 
 9     private String name;
10 
11     public String getName() {
12         return name;
13     }
14 
15     public void setName(String name) {
16         this.name = name;
17     }
18 }

 

The main thread waits (this is known from the code, no problem)

 1 public static void main(String[] args) throws InterruptedException {
 2         Entity entity = new Entity();
 3         Thread thread = new Thread(new MyRunnable(entity));
 4         thread.start();
 5         // Get return value of child thread: main thread wait method
 6         while (entity.getName() == null){
 7             Thread.sleep(1000);
 8         }
 9         System.out.println(entity.getName());
10     }

 

The Join method blocks the current thread to wait for the child thread to finish executing

1 public static void main(String[] args) throws InterruptedException {
2         Entity entity = new Entity();
3         Thread thread = new Thread(new MyRunnable(entity));
4         thread.start();
5         // Get the return value of the child thread: Thread Of join Method to block the main thread until the child thread returns
6         thread.join();
7         System.out.println(entity.getName());
8     }

 

By implementing the Callable interface

There are two cases, through FutureTask or thread pool.

  

  FutureTask

1 @SuppressWarnings("all")
2     public static void main(String[] args) throws ExecutionException, InterruptedException {
3         FutureTask futureTask = new FutureTask(new MyCallable());
4         Thread thread = new Thread(futureTask);
5         thread.start();
6         if(!futureTask.isDone())
7             System.out.println("task has not finished!");
8         System.out.println(futureTask.get());
9     }

  

Thread pool

1 @SuppressWarnings("all")
2     public static void main(String[] args) throws ExecutionException, InterruptedException {
3         ExecutorService executorService = Executors.newCachedThreadPool();
4         Future future = executorService.submit(new MyCallable());
5         if(!future.isDone())
6             System.out.println("task has not finished!");
7         System.out.println(future.get());
8     }

Keywords: Java

Added by lazytiger on Tue, 03 Dec 2019 10:52:31 +0200