下面这个程序中有些不明白的地方
  package testThread;public class DemoJoin {
    public static void main(String[] args){
     NewThread1 t1 = new NewThread1("One");
     NewThread1 t2 = new NewThread1("Two");
     NewThread1 t3 = new NewThread1("Three");
    
     System.out.println("Thread One is alive: "+t1.thread.isAlive());
     System.out.println("Thread Two is alive: "+t2.thread.isAlive());
     System.out.println("Thread Three is alive: "+t3.thread.isAlive());
    
     try{
     System.out.println("Waiting for threads to finish.");
     t1.thread.join();
     t2.thread.join();
     t3.thread.join();
     }catch(InterruptedException e){
     System.out.println("Main thread Interruted.");
     }
     System.out.println("Thread One is alive: "+t1.thread.isAlive());
     System.out.println("Thread Two is alive: "+t2.thread.isAlive());
     System.out.println("Thread Three is alive: "+t3.thread.isAlive());
     System.out.println("Main thread exiting.");
    }
}
class NewThread1 implements Runnable{

private String name;
Thread thread;
public NewThread1(String threadname){
name = threadname;
thread = new Thread(this,name);
System.out.println("New Thread: "+name);
thread.start();
}
public void run(){
try{
for(int i=5;i>0;i--){
System.out.println(name +" : "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println(name +" interrupted.");
}
System.out.println(name +" exiting.");
}
}
运行结果如下:
New Thread: One
New Thread: Two
New Thread: Three
Thread One is alive: true
Thread Two is alive: true
Thread Three is alive: true
Waiting for threads to finish.
Two : 5
One : 5
Three : 5
One : 4
Three : 4
Two : 4
Three : 3
One : 3
Two : 3
Two : 2
Three : 2
One : 2
Two : 1
Three : 1
One : 1
Two exiting.
One exiting.
Three exiting.
Thread One is alive: false
Thread Two is alive: false
Thread Three is alive: false
Main thread exiting.
    请教:
1: 为什么不是单个线程运行完之后再运行下一个线程,join()不是等待线程结束吗?
2: 为什么使用t2.thread.isAlive()这种方法调用isAlive()?
           谢谢!!  

解决方案 »

  1.   

    1.main等到t1t2t3运行完了运行,t1t2t3互不关联。
    2.t2是Runnable类型没有join方法,所以只能通过访问其成员(线程)才可进行线程操作。
      

  2.   

    因为你在NewThread1的构造方法里就thead.start了,也就是说,在t1.thread.join();被执行之前,该线程就开始了,即在t1,t2,t3的thread.join()之前,t1,t2,t3的thread就已经开始运行了,而t1,t2,t3的thread的执行是由CPU随机分配时间的。当主线程执行到t1,t2,t3的thread.join()的时候,实际上t1,t2,t3的thread就有可能都已经运行结束了,所以就有了这样的结果