在实际开发过程中,我们有时候会遇到主线程调用子线程,要等待子线程返回的结果来进行下一步动作的业务。
那么怎么获取子线程返回的值呢,我这里总结了三种方式:
- 主线程等待。
- Join方法等待。
- 实现Callable接口。
Entity类
package com.basic.thread; /**
* @author zhangxingrui
* @create 2019-02-17 22:14
**/
public class Entity { private String name; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
主线程等待(这个一看代码便知晓,没什么问题)
public static void main(String[] args) throws InterruptedException {
Entity entity = new Entity();
Thread thread = new Thread(new MyRunnable(entity));
thread.start();
// 获取子线程的返回值:主线程等待法
while (entity.getName() == null){
Thread.sleep(1000);
}
System.out.println(entity.getName());
}
Join方法阻塞当前线程以等待子线程执行完毕
public static void main(String[] args) throws InterruptedException {
Entity entity = new Entity();
Thread thread = new Thread(new MyRunnable(entity));
thread.start();
// 获取子线程的返回值:Thread的join方法来阻塞主线程,直到子线程返回
thread.join();
System.out.println(entity.getName());
}
通过实现Callable接口
这里又分为两种情况,通过FutureTask或线程池。
FutureTask
@SuppressWarnings("all")
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
if(!futureTask.isDone())
System.out.println("task has not finished!");
System.out.println(futureTask.get());
}
线程池
@SuppressWarnings("all")
public static void main(String[] args) throws ExecutionException, InterruptedException {
ExecutorService executorService = Executors.newCachedThreadPool();
Future future = executorService.submit(new MyCallable());
if(!future.isDone())
System.out.println("task has not finished!");
System.out.println(future.get());
}