在实际开发过程中,我们有时候会遇到主线程调用子线程,要等待子线程返回的结果来进行下一步动作的业务。
那么怎么获取子线程返回的值呢,我这里总结了三种方式:
- 主线程等待
- Join方法等待
- 实现Callable接口
Entity 类
packagecom.basic.thread; /*** @author zhangxingrui* @create 2019-02-17 22:14**/publicclassEntity { privateStringname; publicStringgetName() { returnname; } publicvoidsetName(Stringname) { this.name=name; } }
主线程等待(这个一看代码便知晓,没什么问题)
publicstaticvoidmain(String[] args) throwsInterruptedException { Entityentity=newEntity(); Threadthread=newThread(newMyRunnable(entity)); thread.start(); // 获取子线程的返回值:主线程等待法while (entity.getName() ==null){ Thread.sleep(1000); } System.out.println(entity.getName()); }
Join方法阻塞当前线程以等待子线程执行完毕
publicstaticvoidmain(String[] args) throwsInterruptedException { Entityentity=newEntity(); Threadthread=newThread(newMyRunnable(entity)); thread.start(); // 获取子线程的返回值:Thread的join方法来阻塞主线程,直到子线程返回thread.join(); System.out.println(entity.getName()); }
通过实现Callable接口
这里又分为两种情况,通过FutureTask或线程池。
FutureTask
@SuppressWarnings("all") publicstaticvoidmain(String[] args) throwsExecutionException, InterruptedException { FutureTaskfutureTask=newFutureTask(newMyCallable()); Threadthread=newThread(futureTask); thread.start(); if(!futureTask.isDone()) System.out.println("task has not finished!"); System.out.println(futureTask.get()); }
线程池
@SuppressWarnings("all") publicstaticvoidmain(String[] args) throwsExecutionException, InterruptedException { ExecutorServiceexecutorService=Executors.newCachedThreadPool(); Futurefuture=executorService.submit(newMyCallable()); if(!future.isDone()) System.out.println("task has not finished!"); System.out.println(future.get()); }
Ps:线程本身内部属于同步关系,等执行完之后再得出结果。线程与线程之间属于异步关系。