java多线程中join方法的理解

thread.Join把指定的线程加入到当前线程,可以将两个交替执行的线程合并为顺序执行的线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。

t.join();      //使调用线程 t 在此之前执行完毕。
t.join(1000);  //等待 t 线程,等待时间是1000毫秒

 

先上一段JDK中代码:

Java代码 复制代码  收藏代码
  1. /**  
  2.      *  Waits at most <code>millis</code> milliseconds for this thread to    
  3.      * die. A timeout of <code>0</code> means to wait forever.    
  4.      */  
  5.     //此处A timeout of 0 means to wait forever 字面意思是永远等待,其实是等到t结束后。   
  6.     public final synchronized void join(long millis)    throws InterruptedException {   
  7.         long base = System.currentTimeMillis();   
  8.         long now = 0;   
  9.   
  10.         if (millis < 0) {   
  11.             throw new IllegalArgumentException("timeout value is negative");   
  12.         }   
  13.            
  14.         if (millis == 0) {   
  15.             while (isAlive()) {   
  16.                 wait(0);   
  17.             }   
  18.         } else {   
  19.             while (isAlive()) {   
  20.                 long delay = millis - now;   
  21.                 if (delay <= 0) {   
  22.                     break;   
  23.                 }   
  24.                 wait(delay);   
  25.                 now = System.currentTimeMillis() - base;   
  26.             }   
  27.         }   
  28.     }  
/**
	 *  Waits at most <code>millis</code> milliseconds for this thread to  
     * die. A timeout of <code>0</code> means to wait forever.	
	 */
	//此处A timeout of 0 means to wait forever 字面意思是永远等待,其实是等到t结束后。
	public final synchronized void join(long millis)    throws InterruptedException {
		long base = System.currentTimeMillis();
		long now = 0;

		if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
		}
		
		if (millis == 0) {
			while (isAlive()) {
				wait(0);
			}
		} else {
			while (isAlive()) {
				long delay = millis - now;
				if (delay <= 0) {
					break;
				}
				wait(delay);
				now = System.currentTimeMillis() - base;
			}
		}
    }

 从代码上看,如果线程被生成了,但还未被起动,调用它的 join() 方法是没有作用的,将直接继续向下执行

 

Join方法实现是通过wait(小提示:Object 提供的方法)。 当main线程调用t.join时候,main线程会获得线程对象t的锁(wait 意味着拿到该对象的锁),调用该对象的wait(等待时间),直到该对象唤醒main线程 ,比如退出后。这就意味着main 线程调用t.join时,必须能够拿到线程t对象的锁

 

Example1:

Java代码 复制代码  收藏代码
  1. public class JoinTest implements Runnable{   
  2.        
  3.     public static int a = 0;   
  4.   
  5.     public void run() {   
  6.         for (int k = 0; k < 5; k++) {   
  7.             a = a + 1;   
  8.         }   
  9.     }   
  10.   
  11.     public static void main(String[] args) throws Exception {   
  12.         Runnable r = new JoinTest();   
  13.         Thread t = new Thread(r);   
  14.         t.start();         
  15.         System.out.println(a);   
  16.     }          
  17. }  
public class JoinTest implements Runnable{
	
	public static int a = 0;

	public void run() {
		for (int k = 0; k < 5; k++) {
			a = a + 1;
		}
	}

	public static void main(String[] args) throws Exception {
		Runnable r = new JoinTest();
		Thread t = new Thread(r);
		t.start();		
		System.out.println(a);
	}		
}

 请问程序的输出结果是5吗?答案是:有可能。其实你很难遇到输出5的时候,通常情况下都不是5。当然这也和机器有严重的关系。为什么呢?我的解释是当主线程 main方法执行System.out.println(a);这条语句时,线程还没有真正开始运行,或许正在为它分配资源准备运行。因为为线程分配资源需要时间,而main方法执行完t.start()方法后继续往下执行System.out.println(a);,这个时候得到的结果是a还没有被改变的值0 。怎样才能让输出结果为5!其实很简单,join() 方法提供了这种功能。join() 方法,它能够使调用该方法的线程在此之前执行完毕。

Java代码 复制代码  收藏代码
  1. public static void main(String[] args) throws Exception {   
  2.         Runnable r = new JoinTest();   
  3.         Thread t = new Thread(r);   
  4.         t.start();         
  5.         t.join(); //加入join()   
  6.         System.out.println(a);   
  7.     }     
public static void main(String[] args) throws Exception {
		Runnable r = new JoinTest();
		Thread t = new Thread(r);
		t.start();		
		t.join(); //加入join()
		System.out.println(a);
	}	

 这个时候,程序输入结果始终为5。

为了证明如果不使用t.join()方法,主线程main方法的System.out.println(a);语句将抢先执行,我们可以在main方法中加入一个循环,这个循环用来延长main方法执行的时间,循环次数将严重取决于机器性能。如果循环次数得当,我们也可以看到a的输出结果是5。

Java代码 复制代码  收藏代码
  1. public static void main(String[] args) throws Exception {   
  2.         Runnable r = new JoinTest();   
  3.         Thread t = new Thread(r);   
  4.         t.start();         
  5.         //t.join(); //加入join()   
  6.             /*  
  7.              注意循环体内一定要有实际执行语句,否则编译器或JVM可能优化掉你的这段代码,视这段代  
  8.              码为无效。              
  9.             */  
  10.             for (int i=0; i<300; i++) {                 
  11.                 System.out.print(i);   
  12.             }   
  13.             System.out.println();   
  14.         System.out.println(a);   
  15.     }         
public static void main(String[] args) throws Exception {
		Runnable r = new JoinTest();
		Thread t = new Thread(r);
		t.start();		
		//t.join(); //加入join()
			/*
			 注意循环体内一定要有实际执行语句,否则编译器或JVM可能优化掉你的这段代码,视这段代
			 码为无效。            
			*/
			for (int i=0; i<300; i++) {				
				System.out.print(i);
			}
			System.out.println();
		System.out.println(a);
	}		

 经自己测试,最后a一直是5.

本例参考:http://agio.iteye.com/blog/210600

 

Example2:join(n)

Java代码 复制代码  收藏代码
  1. class RunnableImpl implements Runnable {   
  2.   
  3.     public void run() {   
  4.         try {   
  5.             System.out.println("Begin sleep");   
  6.             Thread.sleep(1000);   
  7.            System.out.println("End sleep");   
  8.         } catch (InterruptedException e) {   
  9.             e.printStackTrace();   
  10.         }   
  11.   
  12.     }   
  13. }  
class RunnableImpl implements Runnable {

    public void run() {
        try {
            System.out.println("Begin sleep");
            Thread.sleep(1000);
           System.out.println("End sleep");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
 
Java代码 复制代码  收藏代码
  1. public class JoinTest{   
  2.        
  3.     public static void main(String[] args) {   
  4.         Thread t = new Thread(new RunnableImpl());   
  5.         t.start();   
  6.         try {   
  7.             t.join(1000);   
  8.             System.out.println("joinFinish");   
  9.         } catch (InterruptedException e) {   
  10.             e.printStackTrace();        
  11.         }   
  12.     }   
  13. }  
public class JoinTest{
	
	public static void main(String[] args) {
        Thread t = new Thread(new RunnableImpl());
        t.start();
        try {
            t.join(1000);
            System.out.println("joinFinish");
        } catch (InterruptedException e) {
            e.printStackTrace();     
        }
    }
}

结果是:
Begin sleep
End sleep
joinFinish

明白了吧,当main线程调用t.join时,main线程等待t线程,等待时间是1000,如果t线程Sleep 2000呢

Java代码 复制代码  收藏代码
  1. class RunnableImpl implements Runnable {   
  2.   
  3.     public void run() {   
  4.         try {   
  5.             System.out.println("Begin sleep");   
  6.             Thread.sleep(2000); //原来为1000   
  7.            System.out.println("End sleep");   
  8.         } catch (InterruptedException e) {   
  9.             e.printStackTrace();   
  10.         }   
  11.   
  12.     }   
  13. }  
class RunnableImpl implements Runnable {

    public void run() {
        try {
            System.out.println("Begin sleep");
            Thread.sleep(2000); //原来为1000
           System.out.println("End sleep");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

结果是:
Begin sleep
joinFinish
End sleep
也就是说main线程只等1000毫秒,不管T什么时候结束.

参考:http://blog.csdn.net/FG2006/archive/2011/05/04/6393768.aspx

 

Example3:

Java代码 复制代码  收藏代码
  1. class CustomThread1 extends Thread {     
  2.        
  3.     public void run() {     
  4.         String threadName = Thread.currentThread().getName();     
  5.         System.out.println(threadName + " start.");     
  6.         try {     
  7.             for (int i = 0; i < 5; i++) {     
  8.                 System.out.println(threadName + " loop at " + i);     
  9.                 Thread.sleep(1000);     
  10.             }     
  11.             System.out.println(threadName + " end.");     
  12.         } catch (Exception e) {     
  13.             System.out.println("Exception from " + threadName + ".run");     
  14.         }     
  15.     }     
  16. }     
  17.   
  18. class CustomThread extends Thread {     
  19.     CustomThread1 t1;     
  20.     public CustomThread(CustomThread1 t1) {             
  21.         this.t1 = t1;     
  22.     }     
  23.     public void run() {     
  24.         String threadName = Thread.currentThread().getName();     
  25.         System.out.println(threadName + " start.");     
  26.         try {     
  27.             t1.join();     
  28.             System.out.println(threadName + " end.");     
  29.         } catch (Exception e) {     
  30.             System.out.println("Exception from " + threadName + ".run");     
  31.         }     
  32.     }     
  33. }     
  34.   
  35. public class JoinTestDemo {     
  36.   
  37.     public static void main(String[] args) {     
  38.         String threadName = Thread.currentThread().getName();     
  39.         System.out.println(threadName + " start.");     
  40.         CustomThread1 t1 = new CustomThread1();     
  41.         CustomThread t = new CustomThread(t1);     
  42.         try {     
  43.             t1.start();     
  44.             Thread.sleep(2000);     
  45.             t.start();     
  46.             t.join(); //在代碼2里,將此處注釋掉     
  47.         } catch (Exception e) {     
  48.             System.out.println("Exception from main");     
  49.         }     
  50.         System.out.println(threadName + " end!");     
  51.     }     
  52. }   
 class CustomThread1 extends Thread {  
     
     public void run() {  
         String threadName = Thread.currentThread().getName();  
         System.out.println(threadName + " start.");  
         try {  
             for (int i = 0; i < 5; i++) {  
                 System.out.println(threadName + " loop at " + i);  
                 Thread.sleep(1000);  
             }  
             System.out.println(threadName + " end.");  
         } catch (Exception e) {  
             System.out.println("Exception from " + threadName + ".run");  
         }  
     }  
 }  

 class CustomThread extends Thread {  
     CustomThread1 t1;  
     public CustomThread(CustomThread1 t1) {          
         this.t1 = t1;  
     }  
     public void run() {  
         String threadName = Thread.currentThread().getName();  
         System.out.println(threadName + " start.");  
         try {  
             t1.join();  
             System.out.println(threadName + " end.");  
         } catch (Exception e) {  
             System.out.println("Exception from " + threadName + ".run");  
         }  
     }  
 }  

 public class JoinTestDemo {  

     public static void main(String[] args) {  
         String threadName = Thread.currentThread().getName();  
         System.out.println(threadName + " start.");  
         CustomThread1 t1 = new CustomThread1();  
         CustomThread t = new CustomThread(t1);  
         try {  
             t1.start();  
             Thread.sleep(2000);  
             t.start();  
             t.join(); //在代碼2里,將此處注釋掉  
         } catch (Exception e) {  
             System.out.println("Exception from main");  
         }  
         System.out.println(threadName + " end!");  
     }  
 } 

 结果:

main start.    //main方法所在的线程起动,但没有马上结束,因为调用t.join();,所以要等到t结束了,此线程才能向下执行。

[CustomThread1] Thread start.     //线程CustomThread1起动
[CustomThread1] Thread loop at 0  //线程CustomThread1执行
[CustomThread1] Thread loop at 1  //线程CustomThread1执行
[CustomThread] Thread start.      //线程CustomThread起动,但没有马上结束,因为调用t1.join();,所以要等到t1结束了,此线程才能向下执行。
[CustomThread1] Thread loop at 2  //线程CustomThread1继续执行
[CustomThread1] Thread loop at 3  //线程CustomThread1继续执行
[CustomThread1] Thread loop at 4  //线程CustomThread1继续执行
[CustomThread1] Thread end.       //线程CustomThread1结束了
[CustomThread] Thread end.        // 线程CustomThread在t1.join();阻塞处起动,向下继续执行的结果

main end!      //线程CustomThread结束,此线程在t.join();阻塞处起动,向下继续执行的结果。

 

将上例中的join注释掉:

Java代码 复制代码  收藏代码
  1. public class JoinTestDemo {     
  2.     public static void main(String[] args) {     
  3.         String threadName = Thread.currentThread().getName();     
  4.         System.out.println(threadName + " start.");     
  5.         CustomThread1 t1 = new CustomThread1();     
  6.         CustomThread t = new CustomThread(t1);     
  7.         try {     
  8.             t1.start();     
  9.             Thread.sleep(2000);     
  10.             t.start();     
  11.            //t.join();   
  12.         } catch (Exception e) {     
  13.             System.out.println("Exception from main");     
  14.         }     
  15.         System.out.println(threadName + " end!");     
  16.     }     
  17. }   
 public class JoinTestDemo {  
     public static void main(String[] args) {  
         String threadName = Thread.currentThread().getName();  
         System.out.println(threadName + " start.");  
         CustomThread1 t1 = new CustomThread1();  
         CustomThread t = new CustomThread(t1);  
         try {  
             t1.start();  
             Thread.sleep(2000);  
             t.start();  
            //t.join();
         } catch (Exception e) {  
             System.out.println("Exception from main");  
         }  
         System.out.println(threadName + " end!");  
     }  
 } 

 结果:

main start. // main方法所在的线程起动,但没有马上结束,这里并不是因为join方法,而是因为Thread.sleep(2000);


[CustomThread1] Thread start.      //线程CustomThread1起动
[CustomThread1] Thread loop at 0   //线程CustomThread1执行
[CustomThread1] Thread loop at 1   //线程CustomThread1执行
main end!   // Thread.sleep(2000);结束,虽然在线程CustomThread执行了t1.join();,但这并不会影响到其他线程(这里main方法所在的线程)。
[CustomThread] Thread start.       //线程CustomThread起动,但没有马上结束,因为调用t1.join();,所以要等到t1结束了,此线程才能向下执行。
[CustomThread1] Thread loop at 2   //线程CustomThread1继续执行
[CustomThread1] Thread loop at 3   //线程CustomThread1继续执行
[CustomThread1] Thread loop at 4   //线程CustomThread1继续执行
[CustomThread1] Thread end.       //线程CustomThread1结束了
[CustomThread] Thread end.        // 线程CustomThread在t1.join();阻塞处起动,向下继续执行的结果

本例参考:http://blog.csdn.net/bzwm/archive/2009/02/12/3881392.aspx

 

Example4

main 线程调用t.join时,必须能够拿到线程t对象的锁,如果拿不到它是无法wait的 ,刚开的例子t.join(1000)不是说明了main线程等待1 秒,如果在它等待之前,其他线程获取了t对象的锁,它等待时间可不就是1毫秒了

Java代码 复制代码  收藏代码
  1. class RunnableImpl implements Runnable {   
  2.   
  3.     public void run() {   
  4.         try {   
  5.             System.out.println("Begin sleep");   
  6.             Thread.sleep(2000);   
  7.             System.out.println("End sleep");   
  8.         } catch (InterruptedException e) {   
  9.             e.printStackTrace();   
  10.         }   
  11.     }   
  12. }  
class RunnableImpl implements Runnable {

    public void run() {
        try {
            System.out.println("Begin sleep");
            Thread.sleep(2000);
            System.out.println("End sleep");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
 
Java代码 复制代码  收藏代码
  1. class ThreadTest extends Thread {   
  2.   
  3.     Thread thread;   
  4.   
  5.     public ThreadTest(Thread thread) {   
  6.         this.thread = thread;   
  7.     }   
  8.   
  9.     @Override  
  10.     public void run() {   
  11.         synchronized (thread) {   
  12.             System.out.println("getObjectLock");   
  13.             try {   
  14.                 Thread.sleep(9000);   
  15.             } catch (InterruptedException ex) {   
  16.              ex.printStackTrace();   
  17.             }   
  18.             System.out.println("ReleaseObjectLock");   
  19.         }   
  20.     }   
  21. }  
class ThreadTest extends Thread {

    Thread thread;

    public ThreadTest(Thread thread) {
        this.thread = thread;
    }

    @Override
    public void run() {
    	synchronized (thread) {
            System.out.println("getObjectLock");
            try {
                Thread.sleep(9000);
            } catch (InterruptedException ex) {
             ex.printStackTrace();
            }
            System.out.println("ReleaseObjectLock");
        }
    }
}
 
Java代码 复制代码  收藏代码
  1. public class JoinTest {   
  2.         public static void main(String[] args) {   
  3.             Thread t = new Thread(new RunnableImpl());   
  4.            new ThreadTest(t).start();   
  5.             t.start();   
  6.             try {   
  7.                 t.join();   
  8.                 System.out.println("joinFinish");   
  9.             } catch (InterruptedException e) {   
  10.                 e.printStackTrace();            
  11.             }   
  12.         }   
  13. }  
public class JoinTest {
	    public static void main(String[] args) {
	        Thread t = new Thread(new RunnableImpl());
	       new ThreadTest(t).start();
	        t.start();
	        try {
	            t.join();
	            System.out.println("joinFinish");
	        } catch (InterruptedException e) {
	            e.printStackTrace();	     
	        }
	    }
}

 结果:
getObjectLock
Begin sleep
End sleep
ReleaseObjectLock
joinFinish

 

在main方法中 通过new  ThreadTest(t).start()实例化 ThreadTest 线程对象, 它 通过 synchronized  (thread) ,获取线程对象t的锁,并Sleep(9000)后释放,这就意味着,即使main方法t.join(1000)等待一秒钟,它必须等待ThreadTest 线程释放t锁后才能进入wait方法中,它实际等待时间是9000+1000ms。

转载自http://uule.iteye.com/blog/1101994

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值