Java 主线程等待子线程执行完再执行

来源:互联网 发布:安卓lua 虚拟按键源码 编辑:程序博客网 时间:2024/05/21 06:44

转载原文处:http://blog.csdn.net/u011270461/article/details/14003951

http://www.cnblogs.com/jsunday/p/3782874.html

http://www.tuicool.com/articles/ZvAFny

因为最近对于线程方面的知识想进行了解,所以查阅了下这方面的知识进行整合。。。。有兴趣的可以进上面原文的地址去看看

1. Demo1 - thread.join()

[java] view plain copy
  1. public class MyTask1 implements Runnable {  
  2.   
  3.     private int num ;  
  4.     public MyTask1(int num){  
  5.         this.num = num;  
  6.     }  
  7.     /* 
  8.      * @see java.lang.Runnable#run() 
  9.      */  
  10.     @Override  
  11.     public void run() {  
  12.         for (int i = 0; i < 2; i++) {  
  13.             System.out.println(num + "----" +i);  
  14.             try {  
  15.                 Thread.sleep(1000);  
  16.             } catch (InterruptedException e) {  
  17.                 e.printStackTrace();  
  18.             }  
  19.         }  
  20.         System.out.println("Thread" + num + " End.");  
  21.     }  
  22. }  

[java] view plain copy
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. public class TestThreadMain1 {  
  5.   
  6.     /**  
  7.      * @Title main  
  8.      * @Description TODO 
  9.      * @Author weizhi2018  
  10.      * @param args         
  11.      * @throws  
  12.      */  
  13.   
  14.     public static void main(String[] args) {  
  15.         long startTime = System.currentTimeMillis();  
  16.         List<Thread> list = new ArrayList<Thread>();  
  17.           
  18.         int num = 5;  
  19.           
  20.         for(int i=0;i<num;i++){  
  21.             Thread thread = new Thread(new MyTask1(i));  
  22.             thread.start();  
  23.             list.add(thread);  
  24.         }  
  25.         for(Thread thread:list){  
  26.             try {  
  27.                 thread.join();  
  28.             } catch (InterruptedException e) {  
  29.                 e.printStackTrace();  
  30.             }  
  31.         }  
  32.         long endTime = System.currentTimeMillis();  
  33.           
  34.         System.out.println("RunTime:"+ (endTime - startTime));  
  35.     }  
  36.   
  37. }  
output:
[java] view plain copy
  1. 0----0  
  2. 4----0  
  3. 2----0  
  4. 3----0  
  5. 1----0  
  6. 1----1  
  7. 2----1  
  8. 3----1  
  9. 4----1  
  10. 0----1  
  11. Thread2 End.  
  12. Thread4 End.  
  13. Thread0 End.  
  14. Thread1 End.  
  15. Thread3 End.  
  16. RunTime:2017  
2. Demo2 - countDownLatch.await()
[java] view plain copy
  1. import java.util.concurrent.CountDownLatch;  
  2.   
  3. public class MyTask2 implements Runnable {  
  4.   
  5.     private CountDownLatch countDownLatch ;  
  6.     public MyTask2(CountDownLatch countDownLatch){  
  7.         this.countDownLatch = countDownLatch;  
  8.     }  
  9.     /* 
  10.      * @see java.lang.Runnable#run() 
  11.      */  
  12.     @Override  
  13.     public void run() {  
  14.         for (int i = 0; i < 2; i++) {  
  15.             try {  
  16.                 Thread.sleep(1000);  
  17.             } catch (InterruptedException e) {  
  18.                 e.printStackTrace();  
  19.             }  
  20.         }  
  21.         System.out.println(Thread.currentThread().getName() + " End.");  
  22.         countDownLatch.countDown();  
  23.     }  
  24. }  

[java] view plain copy
  1. import java.util.concurrent.CountDownLatch;  
  2. import java.util.concurrent.TimeUnit;  
  3.   
  4. public class TestThreadMain2 {  
  5.   
  6.     /**  
  7.      * @Title main  
  8.      * @Description TODO 
  9.      * @Author weizhi2018  
  10.      * @param args         
  11.      * @throws  
  12.      */  
  13.   
  14.     public static void main(String[] args) {  
  15.         long startTime = System.currentTimeMillis();  
  16.           
  17.         int num = 5;  
  18.           
  19.         CountDownLatch countDownLatch = new CountDownLatch(num);    
  20.         for(int i=0;i<num;i++){  
  21.             Thread thread = new Thread(new MyTask2(countDownLatch));  
  22.             thread.start();  
  23.         }  
  24.           
  25.         try {  
  26.             //等待,直到计数器为0  
  27.             countDownLatch.await(10, TimeUnit.SECONDS);  
  28.         } catch (InterruptedException e) {  
  29.             e.printStackTrace();  
  30.         }  
  31.           
  32.         long endTime = System.currentTimeMillis();  
  33.           
  34.         System.out.println("RunTime:"+ (endTime - startTime));  
  35.     }  
  36.   
  37. }  
output:
[java] view plain copy
  1. Thread-4 End.  
  2. Thread-0 End.  
  3. Thread-2 End.  
  4. Thread-3 End.  
  5. Thread-1 End.  
  6. RunTime:2016  
3.主线程等待线程池执行完再执行
[java] view plain copy
  1. import java.util.concurrent.ExecutorService;  
  2. import java.util.concurrent.Executors;  
  3. import java.util.concurrent.TimeUnit;  
  4.   
  5. public class TestThreadPoolMain {  
  6.   
  7.     /**  
  8.      * @Title main  
  9.      * @Description TODO 
  10.      * @Author weizhi2018  
  11.      * @param args         
  12.      * @throws  
  13.      */  
  14.   
  15.     public static void main(String[] args) {  
  16.         long start = System.currentTimeMillis();    
  17.           
  18.         ExecutorService executor = Executors.newFixedThreadPool(2);    
  19.         for(int i = 0; i < 3; i++)    
  20.         {    
  21.             Thread thread = new Thread(new MyTask1(i));    
  22.             executor.execute(thread);    
  23.         }    
  24.         executor.shutdown();    
  25.             
  26.         try    
  27.         {    
  28.             // awaitTermination返回false即超时会继续循环,返回true即线程池中的线程执行完成主线程跳出循环往下执行,每隔10秒循环一次    
  29.             while (!executor.awaitTermination(10, TimeUnit.SECONDS));    
  30.         }    
  31.         catch (InterruptedException e)    
  32.         {    
  33.             e.printStackTrace();    
  34.         }    
  35.             
  36.         long end = System.currentTimeMillis();    
  37.         System.out.println("RunTime:" + (end - start));    
  38.     }  
  39.   
  40. }  

output:

[java] view plain copy
  1. 0----0  
  2. 1----0  
  3. 0----1  
  4. 1----1  
  5. Thread1 End.  
  6. 2----0  
  7. Thread0 End.  
  8. 2----1  
  9. Thread2 End.  
  10. RunTime:4019  

方法4:

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 stubfor (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 blocke.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秒只是一个估值。

方法5:

 FutureDemo

  使用并发包下面的Future模式.

  Future是一个任务执行的结果, 他是一个将来时, 即一个任务执行, 立即异步返回一个Future对象, 等到任务结束的时候, 会把值返回给这个future对象里面. 我们可以使用    ExecutorService接口来提交一个线程.(注意:Future.get()为一个阻塞方法)

  示例:

package com.test;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class FutureDemo {//创建一个容量为1的线程池static ExecutorService executorService = Executors.newFixedThreadPool(1);public static void main(String[] args) throws Exception {//创建线程并提交线程,同时获取一个future对象Thread subThread = new Thread(new SubThread());Future future = executorService.submit(subThread);//主线程处理其他工作,让子线程异步去执行mainWork();//阻塞,等待子线程结束future.get(); System.out.println("Now all thread done!");//关闭线程池executorService.shutdown();}//主线程工作private static void mainWork(){System.out.println("Main thread start work!");try {Thread.sleep(2000L);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("Main Thread work done!");}/** * 子线程类 * @author fuhg */private static class SubThread implements Runnable{public void run() {// TODO Auto-generated method stubSystem.out.println("Sub thread is starting!");try {Thread.sleep(5000L);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("Sub thread is stopping!");}}}

1 0