方法有以下几种:
主线程等待法
使用Thread类的join()阻塞当前线程以等待子线程处理完毕
1、主线程等待法
如下代码
public class CycleWait implements Runnable {
private String name;
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
name = "zhang san";
}
public static void main(String[] args) {
CycleWait cw = new CycleWait();
Thread t = new Thread(cw);
t.start();
System.out.println("name: " + cw.name);
}
}
打印的结果为

将它改造成主线程等待法
public class CycleWait implements Runnable {
private String name;
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
name = "zhang san";
}
public static void main(String[] args) throws InterruptedException {
CycleWait cw = new CycleWait();
Thread t = new Thread(cw);
t.start();
while (cw.name == null){
Thread.sleep(100);
}
System.out.println("name: " + cw.name);
}
}
这样,5秒后就能打印name的值

2、使用Thread类的join()阻塞当前线程以等待子线程处理完毕
修改上上面的方法

原文:https://www.cnblogs.com/linlf03/p/12112790.html