Java并发编程原理与实战六:主线程等待子线程解决方案
本文将研究的是主线程等待所有子线程执行完成之后再继续往下执行的解决方案
public class TestThread extends Thread { public void run() { System.out.println(this.getName() + "子线程开始"); try { // 子线程休眠五秒 Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.getName() + "子线程结束"); } }
首先是一个线程,它执行完成需要5秒。
1、主线程等待一个子线程
public class Main { public static void main(String[] args) { long start = System.currentTimeMillis(); Thread thread = new TestThread(); thread.start(); long end = System.currentTimeMillis(); System.out.println("子线程执行时长:" + (end - start)); } }
在主线程中,需要等待子线程执行完成。但是执行上面的main发现并不是想要的结果:
子线程执行时长:0
Thread-0子线程开始
Thread-0子线程结束
很明显主线程和子线程是并发执行的,主线程并没有等待。
对于只有一个子线程,如果主线程需要等待子线程执行完成,再继续向下执行,可以使用Thread的join()方法。join()方法会阻塞主线程继续向下执行。
public class Main { public static void main(String[] args) { long start = System.currentTimeMillis(); Thread thread = new TestThread(); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("子线程执行时长:" + (end - start)); } }
执行结果:
Thread-0子线程开始
Thread-0子线程结束
子线程执行时长:5000
注意:join()要在start()方法之后调用。
2、主线程等待多个子线程
比如主线程需要等待5个子线程。这5个线程之间是并发执行。
public class Main { public static void main(String[] args) { long start = System.currentTimeMillis(); for(int i = 0; i < 5; i++) { Thread thread = new TestThread(); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } long end = System.currentTimeMillis(); System.out.println("子线程执行时长:" + (end - start)); } }
在上面的代码套上一个for循环,执行结果:
Thread-0子线程开始
Thread-0子线程结束
Thread-1子线程开始
Thread-1子线程结束
Thread-2子线程开始
Thread-2子线程结束
Thread-3子线程开始
Thread-3子线程结束
Thread-4子线程开始
Thread-4子线程结束
子线程执行时长:25000
由于thread.join()阻塞了主线程继续执行,导致for循环一次就需要等待一个子线程执行完成,而下一个子线程不能立即start(),5个子线程不能并发。
要想子线程之间能并发执行,那么需要在所有子线程start()后,在执行所有子线程的join()方法。
public class Main { public static void main(String[] args) { long start = System.currentTimeMillis(); List<Thread> list = new ArrayList<Thread>(); for(int i = 0; i < 5; i++) { Thread thread = new TestThread(); thread.start(); list.add(thread); } try { for(Thread thread : list) { thread.join(); } } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("子线程执行时长:" + (end - start)); } }
执行结果:
Thread-0子线程开始
Thread-3子线程开始
Thread-1子线程开始
Thread-2子线程开始
Thread-4子线程开始
Thread-3子线程结束
Thread-0子线程结束
Thread-2子线程结束
Thread-1子线程结束
Thread-4子线程结束
子线程执行时长:5000
3、主线程等待多个子线程(CountDownLatch实现)
CountDownLatch是Java.util.concurrent中的一个同步辅助类,可以把它看做一个倒数计数器,就像神舟十号发射时倒数:10,9,8,7….2,1,0,走你。初始化时先设置一个倒数计数初始值,每调用一次countDown()方法,倒数值减一,await()方法会阻塞当前进程,直到倒数至0。
同样还是主线程等待5个并发的子线程。修改上面的代码,在主线程中,创建一个初始值为5的CountDownLatch,并传给每个子线程,在每个子线程最后调用countDown()方法对倒数器减1,当5个子线程等执行完成,那么CountDownLatch也就倒数完成,主线程调用await()方法等待5个子线程执行完成。
修改MyThread接收传入的CountDownLatch:
public class TestThread extends Thread { private CountDownLatch countDownLatch; public TestThread(CountDownLatch countDownLatch) { this.countDownLatch = countDownLatch; } public void run() { System.out.println(this.getName() + "子线程开始"); try { // 子线程休眠五秒 Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(this.getName() + "子线程结束"); // 倒数器减1 countDownLatch.countDown(); } }
修改main:
public class Main { public static void main(String[] args) { long start = System.currentTimeMillis(); // 创建一个初始值为5的倒数计数器 CountDownLatch countDownLatch = new CountDownLatch(5); for(int i = 0; i < 5; i++) { Thread thread = new TestThread(countDownLatch); thread.start(); } try { // 阻塞当前线程,直到倒数计数器倒数到0 countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("子线程执行时长:" + (end - start)); } }
执行结果:
Thread-0子线程开始
Thread-2子线程开始
Thread-1子线程开始
Thread-3子线程开始
Thread-4子线程开始
Thread-2子线程结束
Thread-4子线程结束
Thread-1子线程结束
Thread-0子线程结束
Thread-3子线程结束
子线程执行时长:5000
注意:如果子线程中会有异常,那么countDownLatch.countDown()应该写在finally里面,这样才能保证异常后也能对计数器减1,不会让主线程永远等待。
另外,await()方法还有一个实用的重载方法:public booleanawait(long timeout, TimeUnit unit),设置超时时间。
例如上面的代码,想要设置超时时间10秒,到了10秒无论是否倒数完成到0,都会不再阻塞主线程。返回值是boolean类型,如果是超时返回false,如果计数到达0没有超时返回true。
// 设置超时时间为10秒 boolean timeoutFlag = countDownLatch.await(10,TimeUnit.SECONDS); if(timeoutFlag) { System.out.println("所有子线程执行完成"); } else { System.out.println("超时"); }
4、主线程等待线程池
Java线程池java.util.concurrent.ExecutorService是很好用的多线程管理方式。ExecutorService的一个方法boolean awaitTermination(long timeout, TimeUnit unit),即阻塞主线程,等待线程池的所有线程执行完成,用法和上面所说的CountDownLatch的public boolean await(long timeout,TimeUnit unit)类似,参数设置一个超时时间,返回值是boolean类型,如果超时返回false,如果线程池中的线程全部执行完成,返回true。
由于ExecutorService没有类似CountDownLatch的无参数的await()方法,只能通过awaitTermination来实现主线程等待线程池。
public class Main { public static void main(String[] args) { long start = System.currentTimeMillis(); // 创建一个同时允许两个线程并发执行的线程池 ExecutorService executor = Executors.newFixedThreadPool(2); for(int i = 0; i < 5; i++) { Thread thread = new TestThread(); executor.execute(thread); } executor.shutdown(); try { // awaitTermination返回false即超时会继续循环,返回true即线程池中的线程执行完成主线程跳出循环往下执行,每隔10秒循环一次 while (!executor.awaitTermination(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { e.printStackTrace(); } long end = System.currentTimeMillis(); System.out.println("子线程执行时长:" + (end - start)); } }
执行结果:
Thread-0子线程开始
Thread-1子线程开始
Thread-0子线程结束
Thread-2子线程开始
Thread-1子线程结束
Thread-3子线程开始
Thread-2子线程结束
Thread-4子线程开始
Thread-3子线程结束
Thread-4子线程结束
子线程执行时长:15000
另外,while(!executor.isTerminated())也可以替代上面的while (!executor.awaitTermination(10,TimeUnit.SECONDS)),isTerminated()是用来判断线程池是否执行完成。但是二者比较我认为还是awaitTermination更好,它有一个超时时间可以控制每隔多久循环一次,而不是一直在循环来消耗性能。
5.其它方案参考:
/** * 子线程类 * @author Administrator * */ public class SubThread implements Runnable{ private int status = 99; //99-初始化 0-执行成功 1-执行失败 public void run() { System.out.println("开始执行..."); try{ Thread.sleep(2000); }catch(Exception e){ e.printStackTrace(); } status=0; System.out.println("执行完毕..."); } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } }
/** * 主线程类 * @author Administrator * */ public class MainThread { private List<SubThread> subThreadList = new ArrayList<SubThread>(); /** * 创建子线程 * @return */ public SubThread createSubThread(){ SubThread subThread = new SubThread(); subThreadList.add(new SubThread()); return subThread; } public boolean start(){ for(SubThread subThread : subThreadList){ new Thread(subThread).start(); } /** * 监控所有子线程是否执行完毕 */ boolean continueFlag = true; while(continueFlag){ for(SubThread subThread : subThreadList){ if(subThread.getStatus()==99){ continueFlag = true; break; } continueFlag = false; } } /** * 判断子线程的执行结果 */ boolean result = true; for(SubThread subThread : subThreadList){ if(subThread.getStatus()!=0){ result = false; break; } } return result; } }
测试代码:
public static void main(String[] args) { MainThread main = new MainThread(); main.createSubThread(); main.createSubThread(); main.createSubThread(); boolean result = main.start(); System.out.println(result); }
/** * 计数器类 * @author Administrator * */ public class CountLauncher { private int count; public CountLauncher(int count){ this.count = count; } public synchronized void countDown(){ count --; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
/** * 子线程类 * @author Administrator * */ public class SubThread implements Runnable{ /** * 计数器类对象实例 */ private CountLauncher countLauncher; private int status = 99; //99-初始化 0-执行成功 1-执行失败 public void run() { System.out.println("开始执行..."); try{ Thread.sleep(2000); }catch(Exception e){ e.printStackTrace(); } status=0; System.out.println("执行完毕..."); countLauncher.countDown(); } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public CountLauncher getCountLauncher() { return countLauncher; } public void setCountLauncher(CountLauncher countLauncher) { this.countLauncher = countLauncher; } }
/** * 主线程类 * @author Administrator * */ public class MainThread { private List<SubThread> subThreadList = new ArrayList<SubThread>(); /** * 创建子线程 * @return */ public synchronized SubThread createSubThread(){ SubThread subThread = new SubThread(); subThreadList.add(new SubThread()); return subThread; } public boolean start(){ CountLauncher countLauncher = new CountLauncher(subThreadList.size()); for(SubThread subThread : subThreadList){ subThread.setCountLauncher(countLauncher); new Thread(subThread).start(); } while(countLauncher.getCount()>0){ System.out.println(countLauncher.getCount()); } /** * 判断子线程的执行结果 */ boolean result = true; for(SubThread subThread : subThreadList){ if(subThread.getStatus()!=0){ result = false; break; } } return result; } /** * 测试实例 */ public static void main(String[] args) { MainThread main = new MainThread(); main.createSubThread(); main.createSubThread(); main.createSubThread(); boolean result = main.start(); System.out.println(result); } }