我已经创建了简单的程序来测试Java中的线程。我希望它可以无限地打印我的数字,如123123123123123.不知道为什么,但是目前它在一个循环完成后仅停止213。有人知道为什么Java中的线程
public class Main {
int number;
public Main(int number){
}
public static void main(String[] args) {
new Infinite(2).start();
new Infinite(1).start();
new Infinite(3).start();
}
}
class Infinite extends Thread {
static int which=1;
static int order=1;
int id;
int number;
Object console = new Object();
public Infinite(int number){
id = which;
which++;
this.number = number;
}
@Override
public void run(){
while(1==1){
synchronized(console){
if(order == id){
System.out.print(number);
order++;
if(order >= which){
order = 1;
}
try{
console.notifyAll();
console.wait();
}
catch(Exception e)
{}
}
else {
try{
console.notifyAll();
console.wait();
}
catch(Exception e)
{}
}
}
try{Thread.sleep(0);} catch(Exception e) {}
}
}
}
这就是我的想法。事实上,当我复制相同的代码并删除了.wait()和.notifyAll()时,我停止了程序运行时,我的控制台上印着一串数字。 – npinti 2010-05-26 17:51:13