这是 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 才能运行。 请教一下大家
<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 才能运行。 请教一下大家
除非让tf里的run等待匿名类里的run
你没有在go里面对那里创建的Thread进行join()。
调用join()不起作用啊,把go()改为run() main中用start()启动应该行了
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();
}
}