Java中的线程

owc*_*wca 2 java multithreading

我已经创建了一个简单的程序来测试Java中的Threads.我想要它无限打印我的数字,如123123123123123.Dunno为什么,但目前它只停止一个周期后完成213.谁知道为什么?

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) {}
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ris 9

您的每个Infinite实例都在同步,然后等待自己的consoleObject 上的通知.一旦线程进入console.wait(),它就不会继续.

你似乎希望它们都在同一个对象上同步 - 所以你需要,例如,make consolestatic.