本文介绍两种主线程等待子线程的实现方式,以5个子线程来说明:
1、使用Thread的join()方法,join()方法会阻塞主线程继续向下执行。
2、使用Java.util.concurrent中的CountDownLatch,是一个倒数计数器。初始化时先设置一个倒数计数初始值,每调用一次countDown()方法,倒数值减一,他的await()方法会阻塞当前进程,直到倒数至0。
public class AppMain { public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
long start = System.currentTimeMillis() ;
System.out.println();
ArrayList<Thread> arrayList = new ArrayList<>();
for(int i = ;i<;i++)
{
myThread m1 = new myThread();
m1.start();
m1.join();
myThread2 m2 = new myThread2();
m2.start();
m2.join();
}
long end = System.currentTimeMillis();
long endure = end-start;
System.out.println("耗时:"+endure);
} }
输出:
Thread-172 :1111 : 111
Thread-173 :2222 : 222
Thread-174 :1111 : 111
Thread-175 :2222 : 222
Thread-176 :1111 : 111
Thread-177 :2222 : 222
Thread-178 :1111 : 111
Thread-179 :2222 : 222
Thread-180 :1111 : 111
Thread-181 :2222 : 222
Thread-182 :1111 : 111
Thread-183 :2222 : 222
Thread-184 :1111 : 111
Thread-185 :2222 : 222
Thread-186 :1111 : 111
Thread-187 :2222 : 222
Thread-188 :1111 : 111
Thread-189 :2222 : 222
Thread-190 :1111 : 111
Thread-191 :2222 : 222
Thread-192 :1111 : 111
Thread-193 :2222 : 222
Thread-194 :1111 : 111
Thread-195 :2222 : 222
Thread-196 :1111 : 111
Thread-197 :2222 : 222
Thread-198 :1111 : 111
Thread-199 :2222 : 222
耗时:68
如果不采用join()方法的话,会先执行完main线程,子线程继续执行。则不会正确打印出耗时时间
输出如下:
Thread-181 :2222 : 222
Thread-182 :1111 : 111
Thread-183 :2222 : 222
Thread-184 :1111 : 111
Thread-185 :2222 : 222
Thread-186 :1111 : 111
Thread-187 :2222 : 222
Thread-188 :1111 : 111
Thread-189 :2222 : 222
Thread-190 :1111 : 111
耗时:68----------------------------------会发现主线程先执行完了
Thread-191 :2222 : 222
Thread-192 :1111 : 111
Thread-193 :2222 : 222
Thread-194 :1111 : 111
Thread-195 :2222 : 222
Thread-196 :1111 : 111
Thread-197 :2222 : 222
Thread-198 :1111 : 111
Thread-199 :2222 : 222