class Callme{
//synchronized void call(String msg){
void call(String msg){
System.out.print("[" + msg);
try{
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Interrupted");
}
System.out.println("]");
}
}class Caller implements Runnable{
String msg;
Callme target;
Thread t;

public Caller(Callme targ,String s){
target = targ;
msg = s ;
t = new Thread(this);
t.start();
}
public void run(){
synchronized(target){
target.call(msg);
}
}
}public class Synch {
public static void main(String args[]){
Callme target = new Callme();
Caller ob1 = new Caller(target,"Hello");
Caller ob2 = new Caller(target,"Synchronized");
Caller ob3 = new Caller(target,"World");
try{    //即使去掉这段try代码,程序的输出也是相同的,这段代码究竟有什么作用呢?
ob1.t.join(); //请高手帮忙指点下迷津,万分感谢  hoho 
ob2.t.join();  
ob3.t.join();
}catch(InterruptedException e){
System.out.println("Interrupted");
}

}
}

解决方案 »

  1.   

    ob2.t.join();的意思是:等待ob2.t这个线程结束。当然是main线程等待。
      

  2.   

    在你的例子里,去掉与否没有关系,但是,如果main线程还要做其他的工作的话,就有作用了。
    比如说吧:
    main(){
      long start = System.currentTimeMillis();  很复杂的操作,开了许多其他的线程  long end=System.currentTimeMillis();  如果要输出程序的运行时间,必须要等到所有的线程都结束,所以,main线程中要调用开启的线程的join方法,等待他们结束
     
    }
      

  3.   

    就是在这里:
    {
    ......
    t1.join();
    t2.join();
    然后再:
    long end=System.currentTimeMillis();
    .....
    }
    这样才可以
      

  4.   

    join()是当前线程等待该线程结束
    你输出结果之所以相同是因为synchronized(target)语句,注释掉后就会输出多种结果了
      

  5.   

    5楼说的也有道理,一开始没看清,不好意思。
    因为,3个线程共享一个Callme对象实例,而调用的时候是用synchronized锁定了这个对象,所以这3个线程只能异步的执行。 而你说的优先级跟这个没有关系。也没有规定必须等待子线程结束主线程才可以结束,我是说有的时候需要这么做。
      

  6.   


    /*
    try{ //即使去掉这段try代码,程序的输出也是相同的,这段代码究竟有什么作用呢?
    ob1.t.join(); //请高手帮忙指点下迷津,万分感谢 hoho 
    ob2.t.join(); 
    ob3.t.join();
    }catch(InterruptedException e){
    System.out.println("Interrupted");
    }
    */
    System.out.println("over");现在你跑跑试试 就更清楚了