下面的例子结果是 Joiner ObjectA 但是我在 ObjectA 中有调用 joiner.join(); 为什么还是 Joiner先显示呢?我试了好几种方法都不行,所以来请教下各位。
import java.util.concurrent.TimeUnit;class Joiner extends Thread{
public Joiner(String name){
super(name);
start();
}
public void run(){
try{
sleep(1000);
}catch(InterruptedException e){
System.out.println("Interrupt");
}
System.out.println("Joiner");
}
}class ObjectA extends Thread{
public Joiner joiner;
public ObjectA(String name, Joiner joiner){
super(name);
this.joiner = joiner;
start();
}
public void run(){
try{
joiner.join();
}catch(InterruptedException e){
System.out.println("Interrupt");
}
System.out.println("ObjectA");
}
}public class ObjectTest2{
public static void main(String[] args){
Joiner j = new Joiner("A");
ObjectA oa = new ObjectA("B", j);
}
}

解决方案 »

  1.   

    你想实现什么效果呢。
    先打印Joiner是正常的啊。
    class Joiner extends Thread{
        public Joiner(String name){
            super(name);
            start();//2.这里启动了此线程,执行run方法
        }
        public void run(){
            try{
                sleep(1000);
            }catch(InterruptedException e){
                System.out.println("Interrupt");
            }
            System.out.println("Joiner");
        }
    }class ObjectA extends Thread{
        public Joiner joiner;
        public ObjectA(String name, Joiner joiner){
            super(name);
            this.joiner = joiner;
            start();//4。起动了此线程转向5
        }
        public void run(){
            try{
                joiner.join();//5.这里之后的代码,只能等待Joiner线程返回了,才会向下执行,所以先打印Joiner。
            }catch(InterruptedException e){
                System.out.println("Interrupt");
            }
            System.out.println("ObjectA");
        }
    }public class ObjectTest2{
        public static void main(String[] args){
            Joiner j = new Joiner("A");//1.转向2
            ObjectA oa = new ObjectA("B", j);//3.转向4
        }
    }
      

  2.   

    joiner.join(); 方法只是对线程说 你注意了 已经连接上了准备跑
    但是线程几时开始跑 就是由操作系统来控制了
      

  3.   

    joiner.join(); 是指的等待Joiner线程执行结速,当然先打Joiner了,改成joiner.start();就会先打ObjectA 
      

  4.   

    恩,我对Thread.join()方法的理解正好反了,谢谢各位。
      

  5.   

    试了一下,好像总是先输出Joiner, 再输出ObjectA,