Topic: 请教Thread类的join()方法的涵义

  Print this page

1.请教Thread类的join()方法的涵义 Copy to clipboard
Posted by: tianningsi
Posted on: 2007-02-06 16:50

JDK的API中只是说"等待线程的结束",不知起什么作用?

2.Re:请教Thread类的join()方法的涵义 [Re: tianningsi] Copy to clipboard
Posted by: cxp108
Posted on: 2007-02-08 10:14

当你调用 thread.join() 的时候,程序就会阻塞在这里,直到thread结束(也就是说至少要等到thread.run()这个方法结束)join()才会返回,程序才能继续运行。

3.Re:请教Thread类的join()方法的涵义 [Re: cxp108] Copy to clipboard
Posted by: tianningsi
Posted on: 2007-02-08 20:46

谢谢cxp108,
以下是测试代码:
/**
* Date:2007-2-7
* JoinTest
* @author Mao
* @version 1.0
*/

public class JoinTest {
  public static void main(String[] args)throws Exception {
    Counter counter1 = new Counter();
    Counter counter2 = new Counter();
    Counter counter3 = new Counter();
    
    counter1.start();
    counter1.join(); //等待counter1结束

    counter2.start();
    counter2.join();

    counter3.start();
  }
}

class Counter extends Thread{
  private int count;

  public void run(){
    while (true){
      System.out.println(this.getName()+(++count));
      try{
        sleep(300);
      }catch(InterruptedException ex){
      }
      if(count == 12)
        return;
    }
  }
}

4.Re:请教Thread类的join()方法的涵义 [Re: tianningsi] Copy to clipboard
Posted by: gumuyang
Posted on: 2007-02-09 08:57

请问楼上的程序中start()和join()各是什么意思?我在API库里怎么找不到?

另外为什么Counter还可以作为子类继承Thread?

5.Re:请教Thread类的join()方法的涵义 [Re: gumuyang] Copy to clipboard
Posted by: tianningsi
Posted on: 2007-02-09 10:28

start()和join()都是Thread类的方法,
Thread在java.lang包中

第二个问题属于Java的作用域的问题(public,protected,private)
Thread作为一个public class,完全可以被继承

6.Re:请教Thread类的join()方法的涵义 [Re: tianningsi] Copy to clipboard
Posted by: gumuyang
Posted on: 2007-02-09 14:47

感谢楼上回答我的问题!

顺便再多嘴问一句:为什么Counter没有定义类就可以Counter counter1 = new Counter();了呢?

如果说Counter是保留类的话,那又为什么可以作为子类?

本人基础确实薄弱,虽然自己知耻后勇,不断看书翻贴,但有很多弱智问题书上就是学不到。还望高手不吝赐教!

7.Re:请教Thread类的join()方法的涵义 [Re: tianningsi] Copy to clipboard
Posted by: tianningsi
Posted on: 2007-02-09 18:20

Counter不是保留类,代码中第二个类就是Counter的定义:
class Counter extends Thread{
......
.....
编译之后就可以给JoinTest类调用了

没关系,谁都是这样,由不懂到熟悉嘛,加油.


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923