java多线程 主线程等子线程执行完毕

来源:互联网 发布:上海mao livehouse知乎 编辑:程序博客网 时间:2024/05/21 10:08

有时候java开发,主线程要等子线程执行完毕的处理结果
主要有两种方法处理
1. 是用thread.join()
2. 是使用线程池 ExecutorService

1 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]执行完毕主线执行。

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

  1. 使用线程池 ExecutorService
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]执行完毕主线执行。
0 0