Thread类中join()方法

来源:互联网 发布:胸大 知乎 编辑:程序博客网 时间:2024/05/21 06:48

Thread类中有一个join()方法,在一个线程中启动另外一个线程的join方法,当前线程将会挂起,而执行被启动的线程,知道被启动的线程执行完毕后,当前线程才开始执行。

下面我们新建两个继承Thread的类,让其中一个线程在另外一个线程中调用join方法

[java] view plain copy
  1. class Thread1 extends Thread  
  2. {  
  3.     public Thread1(String threadName)  
  4.     {     
  5.         super(threadName);  
  6.     }  
  7.       
  8.     public void run()  
  9.     {  
  10.         System.out.println(getName() + "is running");  
  11.         try  
  12.         {  
  13.             sleep(2000);  
  14.         }   
  15.         catch (InterruptedException e)  
  16.         {  
  17.             e.printStackTrace();  
  18.         }  
  19.     }  
  20. }  

[java] view plain copy
  1. class Thread2 extends Thread  
  2. {  
  3.     private Thread1 thread1;  
  4.       
  5.     public Thread2(String threadName, Thread1 thread1)  
  6.     {  
  7.         super(threadName);  
  8.         this.thread1 = thread1;       
  9.     }  
  10.       
  11.     public void run()  
  12.     {  
  13.         System.out.println(getName() +  "is running");  
  14.         try  
  15.         {  
  16.             thread1.start();  
  17.             thread1.join();  
  18.         }   
  19.         catch (InterruptedException e)  
  20.         {  
  21.             e.printStackTrace();  
  22.         }  
  23.         System.out.println("thread2 is over");    
  24.     }  
  25. }  
[java] view plain copy
  1. <pre name="code" class="java">package com.thread;  
  2.   
  3. public class JoinTest  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         Thread1 thread1 = new Thread1("Thread1");  
  8.         Thread2 thread2 = new Thread2("Thread2", thread1);  
  9.         thread2.start();  
  10.     }  
  11. }</pre><br>  
  12. <br>  
  13. <pre></pre>  
  14. 我们在thead2中调用thread1的join()方法,让thread1中断thread2自身的运行,运行程序首先输出thread2 is running,然后输出thread1 is running, 过了两秒钟之后,才输出thread2 is over,这就说明在thread2中调用thread1的join()方法,thread2自身被中断了,转而执行thread1,等待thread1执行完毕之后,再转过来执行thread2<br>  
原创粉丝点击