这是 scjp 上的一道题,原体只适用于一个 instance, 我想给他改成使用与多个 instance, 所以改了一下代码,原本想每个不同instance 都可以顺序打印出 12345,如:12345 12345 12345。, 但没能如愿。 原以为 join() 可以实现这个目的,可以不行,看来我对 join() 的概念没弄特清楚, 请高手执教, 大家讨论下
<code>
public class TestFive extends Thread{
 int x=0;
public  synchronized void foo(){

int current =x;
x=current+1;
System.out.print(x+", ");
}

public  synchronized void go(){
for(int i=0; i<5; i++){
new Thread(){
public void run(){
foo();
System.out.println("----------------" +
"");

}
}.start();
}
}

public static void main(String[] args) throws InterruptedException{
TestFive tf = new TestFive();
tf.go();
tf.join(); //***********************
TestFive tf1 = new TestFive()
         tf1.go();
}
}
</code>
//***************** 原本以为要 tf 完成后 tf1 才能运行。 请教一下大家

解决方案 »

  1.   

    tf.join()等待tf.run()结束,但你并没有tf.start()呀所以顺序没办法保证。初步想,没仔细,你把tf.go改成tf.start(),go里的东西放到run里
      

  2.   

    好像还是差,因为匿名类里的几个run执行没完,testfive的run可能执行完,这样tf1就启动了
    除非让tf里的run等待匿名类里的run
      

  3.   

    解释一下2楼:
    你没有在go里面对那里创建的Thread进行join()。
      

  4.   

    tf和tf1根本就不是线程,TestFive只是个普通类而已
    调用join()不起作用啊,把go()改为run() main中用start()启动应该行了
      

  5.   


    public class File extends Thread{ 
    int x=0; 
    public  synchronized void foo(){ 
    int current =x; 
    x=current+1; 
    System.out.print(x+", "); 


    public synchronized void run(){ 
    for(int i=0; i <5; i++){ 
    foo(); 
    System.out.println("----------------" + "");
    } } 

    public static void main(String[] args) throws InterruptedException{ 
    File tf = new File(); 
    File tf1 = new File(); 
    tf.start(); 
    tf1.join(); //*********************** 
    tf1.start();