獲取Java線程返回值的幾種方式


在實際開發過程中,我們有時候會遇到主線程調用子線程,要等待子線程返回的結果來進行下一步動作的業務。

那么怎么獲取子線程返回的值呢,我這里總結了三種方式:

  1. 主線程等待。
  2. Join方法等待。
  3. 實現Callable接口。

  Entity類

 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 }

 

主線程等待(這個一看代碼便知曉,沒什么問題)

 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         // 獲取子線程的返回值:主線程等待法
 6         while (entity.getName() == null){
 7             Thread.sleep(1000);
 8         }
 9         System.out.println(entity.getName());
10     }

 

  Join方法阻塞當前線程以等待子線程執行完畢

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         // 獲取子線程的返回值:Thread的join方法來阻塞主線程,直到子線程返回
6         thread.join();
7         System.out.println(entity.getName());
8     }

 

  通過實現Callable接口

  這里又分為兩種情況,通過FutureTask或線程池。

  

  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     }

  

  線程池

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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM