Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads in Java

I've created simple program to test Threads in Java. I'd like it to print me numbers infinitely, like 123123123123123. Dunno why, but currently it stops after one cycle finishing 213 only. Anyone knows why ?

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) {}
        }
    }
}
like image 301
sasklacz Avatar asked Mar 23 '26 04:03

sasklacz


1 Answers

Each of your Infinite instances is synchronising on, then waiting for a notification on, its own console Object. Once the thread gets to console.wait(), it's not going to continue.

You seem to want them all to synchronise on the same object - so you'll need to, for example, make console static.

like image 55
Chris Avatar answered Mar 24 '26 18:03

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!