获取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     }

 

转载于:https://www.cnblogs.com/alinainai/p/10409540.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值