Java主线程等待所有子线程执行完毕再执行解决办法集

Java主线程等待所有子线程执行完毕在执行,其实在我们的工作中经常的用到,比如说主线程要返回一个响应用户的值,但这个值得赋值过程是由过个子线程来完成的(模拟一个实际开发的情景),所以主线程必须等待子线程执行完毕,再响应用户;否则,响应用户的是一个无意义的值。

  那么如何确保所有的子线程执行完毕了。一般的有如下方法:

  1  让主线程等待,或着睡眠几分钟。用Thread.sleep()或者TimeUnit.SECONDS.sleep(5);

  如下:

package andy.thread.traditional.test;

import java.util.concurrent.TimeUnit;

/**
 * @author Zhang,Tianyou
 * @version 2014年11月21日 下午11:15:27
 */

public class ThreadSubMain1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		for (int i = 0; i < 10; i++) {

			new Thread(new Runnable() {
				public void run() {

					try {
						Thread.sleep(1000);
						// 模拟子线程任务
					} catch (InterruptedException e) {
					}
					System.out.println("子线程" + Thread.currentThread() + "执行完毕");

				}
			}).start();
			
		}

		try {
			// 等待全部子线程执行完毕
			TimeUnit.SECONDS.sleep(5);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("主线执行。");
	}

}


效果如下:

子线程Thread[Thread-1,5,main]执行完毕
子线程Thread[Thread-3,5,main]执行完毕
子线程Thread[Thread-5,5,main]执行完毕
子线程Thread[Thread-7,5,main]执行完毕
子线程Thread[Thread-9,5,main]执行完毕
子线程Thread[Thread-0,5,main]执行完毕
子线程Thread[Thread-2,5,main]执行完毕
子线程Thread[Thread-4,5,main]执行完毕
子线程Thread[Thread-6,5,main]执行完毕
子线程Thread[Thread-8,5,main]执行完毕
主线执行。

 此方主线程只是睡了5秒,但是不能保证全部的子线程执行完成,所以这儿的5秒只是一个估值。


2 使用Thread的join()等待所有的子线程执行完毕,主线程在执行

 实现 如下:

package andy.thread.traditional.test;

import java.util.Vector;

/**
 * @author Zhang,Tianyou
 * @version 2014年11月21日 下午11:15:27
 */

public class ThreadSubMain2 {

	public static void main(String[] args) {
		// 使用线程安全的Vector 
		Vector<Thread> threads = new Vector<Thread>();
		for (int i = 0; i < 10; i++) {

			Thread iThread = new Thread(new Runnable() {
				public void run() {

					try {
						Thread.sleep(1000);
						// 模拟子线程任务
					} catch (InterruptedException e) {
					}
					System.out.println("子线程" + Thread.currentThread() + "执行完毕");

				}
			});

			threads.add(iThread);
			iThread.start();
		}

		for (Thread iThread : threads) {
			try {
				// 等待所有线程执行完毕
				iThread.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println("主线执行。");
	}

}

执行结果也是如下:

子线程Thread[Thread-1,5,main]执行完毕
子线程Thread[Thread-2,5,main]执行完毕
子线程Thread[Thread-0,5,main]执行完毕
子线程Thread[Thread-3,5,main]执行完毕
子线程Thread[Thread-4,5,main]执行完毕
子线程Thread[Thread-9,5,main]执行完毕
子线程Thread[Thread-7,5,main]执行完毕
子线程Thread[Thread-5,5,main]执行完毕
子线程Thread[Thread-8,5,main]执行完毕
子线程Thread[Thread-6,5,main]执行完毕
主线执行。

 这种方式符合要求,它能够等待所有的子线程执行完,主线程才会执行。


3 使用ExecutorService线程池,等待所有任务执行完毕再执行主线程,awaitTermination

   awaitTermination(long timeout,TimeUnit unit)
          请求关闭、发生超时或者当前线程中断,无论哪一个首先发生之后,都将导致阻塞,直到所有任务完成执行。

package andy.thread.traditional.test;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author Zhang,Tianyou
 * @version 2014年11月21日 下午11:15:27
 */

public class ThreadSubMain3 {

	public static void main(String[] args) {
		// 定义一个缓冲的线程值 线程池的大小根据任务变化
		ExecutorService threadPool = Executors.newCachedThreadPool();
		for (int i = 0; i < 10; i++) {

			threadPool.execute(new Runnable() {
				public void run() {

					try {
						Thread.sleep(1000);
						// 模拟子线程任务
					} catch (InterruptedException e) {
					}
					System.out.println("子线程" + Thread.currentThread() + "执行完毕");

				}
			});

		}

		// 启动一次顺序关闭,执行以前提交的任务,但不接受新任务。
		threadPool.shutdown();

		try {
			// 请求关闭、发生超时或者当前线程中断,无论哪一个首先发生之后,都将导致阻塞,直到所有任务完成执行
			// 设置最长等待10秒
			threadPool.awaitTermination(10, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			//
			e.printStackTrace();
		}

		System.out.println("主线执行。");
	}

}

执行结果如下:

子线程Thread[pool-1-thread-4,5,main]执行完毕
子线程Thread[pool-1-thread-1,5,main]执行完毕
子线程Thread[pool-1-thread-7,5,main]执行完毕
子线程Thread[pool-1-thread-6,5,main]执行完毕
子线程Thread[pool-1-thread-5,5,main]执行完毕
子线程Thread[pool-1-thread-2,5,main]执行完毕
子线程Thread[pool-1-thread-3,5,main]执行完毕
子线程Thread[pool-1-thread-8,5,main]执行完毕
子线程Thread[pool-1-thread-10,5,main]执行完毕
子线程Thread[pool-1-thread-9,5,main]执行完毕
主线执行。


这种方法和方法2一样,将等待所有子线程执行完毕之后才执行主线程。


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值