线程从开始到结束,都会有些比较耗时的操作,例如在多线程场景中,往往主线程执行结束了,子线程还没执行完毕那么子线程的任务结果是不会返回,只能返回主线程所操作的任务,下面我们给 出几种主线程等待子线程执行结束在返回的操作。
先看看正常执行的顺序:主线程开始-》主线程结束-》子线程开始-》子线程结束
直接就把主线程跑完了
一、使用 join()方法
下面我们使用join()来看看执行的顺序:主线程开始-》子线程开始-》子线程结束-》主线程结束
public static void main(String[] args) {
Thread t1 =
new Thread(
new Runnable() {
@Override
public void run() {
try {
System.out.println("子线程开始");
//休眠两秒
Thread.sleep(2000);
System.out.println("子线程结束");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
System.out.println("主线程开启");
try {
t1.start();
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程结束");
}
二、使用CountDownLatch
看看执行结果与上面一致
代码如下(示例):
public static void main(String[] args) {
final CountDownLatch count = new CountDownLatch(1);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("子线程开始");
//休眠两秒
Thread.sleep(2000);
System.out.println("子线程结束");
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
count.countDown();
}
}
});
System.out.println("主线程开启");
try {
t1.start();
count.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("主线程结束");
}