java-threadsthread-synchronizationshared-objects

Java Thread Synchronization 101


Thinking that the shared object Control would enforce that n threads (Number) display in order, they clearly do not:

Number:

public class Number implements Runnable {

    private int i_;
    private Control control;

    public Number(int i, Control c) {
        i_ = i;
        control = c;
    }

    public void start() {
        new Thread(this).start();
    }

    public void run() {
        synchronized(control) {
            control.call(i_);
        }
    }
}

Control:

public class Control {

    private int i_ = 0;

    public void call(int i) {

        if(i != i_) {
            try {
                wait();
            }
            catch(Exception e) {}
        }

        System.out.println(i);
        i_++; // next, please                                                                                                                                                                                   
        notify();
    }
}

Test harness (main):

public class RunNumbers {

    public static void main(String args[]) {

        int n = 0;
        if (args.length > 0) {
            n = Integer.parseInt(args[0]);
        }

        Control c = new Control();
        for(int i = 0; i < n; ++i) {
            new Number(i, c).start();
        }
    }
}

Any ideas?


Solution

  • The above was arrived to by piecing together several tutorials involving only a pair of threads (without really knowing what is going on) --- resulting in the failure to scale everything up to more than two threads.

    After a bit more research, the above can be fixed by changing 2 lines in Control.java:

    (a) change if(i != i_) { to while(i != i_) {

    (b) change notify(); to notifyAll();