有时候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]执行完毕
主线执行。
这种方式符合要求,它能够等待所有的子线程执行完,主线程才会执行。
- 使用线程池 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]执行完毕
主线执行。
本文介绍了在Java开发中,当主线程需要等待子线程执行完毕后再继续执行的情况。主要讨论了两种实现方式:1. 使用`thread.join()`方法,此方法能使主线程阻塞,直到所有子线程执行完毕;2. 利用线程池`ExecutorService`,通过调用`shutdown()`和`awaitTermination()`方法来等待子线程执行结束。这两种方法都可以确保主线程正确地等待子线程完成任务。
1635

被折叠的 条评论
为什么被折叠?



