- 主线程等待法
- 使用Thread类的join()方法阻塞当前线程以等待子线程处理完毕
- 通过Callable接口实现:通过FutureTask或线程池获取
方法一
MyRunnable类
//子线程,默认value为null,等待3s之后改变其值
public class MyRunnable implements Runnable{
private String value;
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
value = "libai";
}
public String getValue() {
return value;
}
}
测试
public class Main1 {
public static void main(String[] args) throws InterruptedException {
MyRunnable mr = new MyRunnable();
Thread thread = new Thread(mr);
thread.start();
while (mr.getValue() == null){
Thread.sleep(100);
}
System.out.println("value=" + mr.getValue());
}
}
结果
方法二
测试
public class Main1 {
public static void main(String[] args) throws InterruptedException {
MyRunnable mr = new MyRunnable();
Thread thread = new Thread(mr);
thread.start();
thread.join();
System.out.println("value=" + mr.getValue());
}
}
结果
方法三
MyCallable类
public class MyCallable implements Callable<String> {
private String value;
@Override
public String call() throws Exception {
Thread.sleep(3000);
value = "libai";
return value;
}
}
测试
public class Main2 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable callable = new MyCallable();
FutureTask<String> futureTask = new FutureTask<>(callable);
new Thread(futureTask).start();
if (!futureTask.isDone()) {
System.out.println("waiting...");
}
System.out.println("value=" + futureTask.get());
}
}
或者
public class Main3 {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
Future<String> future = executorService.submit(new MyCallable());
if (!future.isDone()) {
System.out.println("waiting...");
}
try {
System.out.println("value=" + future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
结果