等待其他线程执行完成的几种方式
方式一
使用Thread.join()方法
public class CalculationThread implements Runnable {
private int count;
public CalculationThread(int count) {
this.count = count;
}
@Override
public void run() {
try {
if(count > 0) {
Thread.sleep(1000 * count);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("计算 硬盘 大小 count = "+count + "toString=" + toString());
}
}
public class ThreadJoinTest {
public static void main(String[] args) {
// 方式一
for (int i=0;i < 5;i++) {
CalculationThread thread = new CalculationThread(i);
Thread wrapperThread = new Thread(thread);
wrapperThread.start();
try {
wrapperThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
方式二
使用CountDownLatch倒计时类
public class CountDownThread extends Thread {
private int count;
private CountDownLatch mCountDownLatch;
public CountDownThread(int count,CountDownLatch countDownLatch) {
this.count = count;
this.mCountDownLatch = countDownLatch;
}
@Override
public void run() {
try {
if(count > 0) {
Thread.sleep(1000 * count);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("计算 硬盘 大小 count = "+count + "toString=" + toString());
mCountDownLatch.countDown();
}
}
public class CountDownLatchTest {
public static void main(String[] args) {
CountDownLatch countDownLatch = new CountDownLatch(6);
for (int i=0;i<6;i++) {
Thread thread = new CountDownThread(i,countDownLatch);
thread.start();
}
try {
// 会阻塞主线程
countDownLatch.await();
// 超过10秒就不再等待,如果不再等待则会释放主线程
// boolean await = countDownLatch.await(2, TimeUnit.SECONDS);
// System.out.println(await);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
方法三
使用线程池的awaitTermination()方法
public class ThreadPoolTest {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(4);
for (int i=0;i < 4;i++) {
CalculationThread thread = new CalculationThread(i);
service.submit(thread);
}
// 执行线程池中的任务,不再接收新的任务
service.shutdown();
try {
// 在一定时间内,如果线程池中的任务全部执行完成,则返回true
boolean awaitTermination = service.awaitTermination(10,TimeUnit.SECONDS);
while (!awaitTermination) {
boolean isTerminated = service.isTerminated();
System.out.println("继续循环" + isTerminated);
if(isTerminated) {
break;
}
}
System.out.println("执行完成");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}