`
fandayrockworld
  • 浏览: 308524 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

基础知识一大堆之Thread:join

阅读更多

相信大家看api文档是不会搞清楚join()这个方法真正意义的,下面我用几行代码尽量言简意赅的说一下:

 

public class ThreadTest {
	public static void main(String[] args) throws Exception {
		ThreadTest tt = new ThreadTest();
		
		tt.testJoin();
	}
	
	public void testJoin() throws Exception {
		MyThread mt1 = new MyThread();
		mt1.start();
		
		long start = System.currentTimeMillis();
		
		// mt1.join();
		
		System.out.printf("testJoin over. Cost %d ms.\n", System.currentTimeMillis() - start);
	}
}

class MyThread extends Thread {
	public void run() {
		System.out.println(this.getName() + " start...");
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println(this.getName() + " over.");
	}
}

运行上面的代码,得到的结果可能如下(第一句和第二句位置不固定)

Thread-0 start...
testJoin over. Cost 0 ms. //是的,这句会先执行
Thread-0 over.

是的,

System.out.printf("testJoin over. Cost %d ms.\n", System.currentTimeMillis() - start);

 这一句会先于

System.out.println(this.getName() + " over.");

 

 执行,且,打印出的 Cost 会是0ms。

 

这是因为 执行 mt1.start(); 后,会启一个Thread-0线程,主线程继续执行,而Thread-0线程则sleep 1000ms,

所以,就会出现上面的状况。

 

那么,我们将上面程序中 注释掉的那句mt1.join(); 加上,就会出现下面的结果:

Thread-0 start...
Thread-0 over.
testJoin over. Cost 1000 ms.

 

再看API文档中对join()方法的描述:等待该线程终止。  该线程是哪个线程?在上面的代码中,指的就是mt1.start();所创造出来的线程。

 

----------延伸-----------

 

而,如果我们给join 加上 参数,

第一次是: 

 

mt1.join(30);

 

 结果是:

 

Thread-0 start...
testJoin over. Cost 31 ms.
Thread-0 over.

 

 第二次是:

 

mt1.join(2000);

 结果是:

 

 

Thread-0 start...
Thread-0 over.
testJoin over. Cost 1000 ms.// 这里是1000,而不是2000
 

 

分析一下原因:

 

两种状况可导致join(long millis)方法退出:  主线程isAlive==false;等待毫秒数>millis。

 

 

PS:语言表达能力有限,可能说的不清楚。。。

 

1
0
分享到:
评论
1 楼 duchq044 2012-02-03  
不清楚你还说

相关推荐

Global site tag (gtag.js) - Google Analytics