improper output of synchronization in java

40 Views Asked by At

In the code, the thread output is not properly synchronized. The output should be the numbers in increasing order.

here is the code

public class Prog {

    public static void main(String[] args) {
        Thread a = new Thread(new Writer(), "A");
        Thread b = new Thread(new Writer(), "B");
        Thread c = new Thread(new Writer(), "C");
        a.start();
        b.start();
        c.start();
    }

    static class Writer implements Runnable {

        private static int count;

        @Override
        public void run() {
            while (count < 5) {
                show();
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException ex) {
            }
        }

        private synchronized void show() {
            System.out.println(Thread.currentThread().getName() + ":\t" + ++count);
        }
    }
}

One output of this code is:

B:  2
B:  4
C:  3
A:  2
B:  5

whereas expected output is:

B:  1
B:  2
C:  3
A:  4
B:  5

What am I missing? Please help.

1

There are 1 best solutions below

1
On BEST ANSWER

Each Writer synchronizes (implicitly) on itself - so you have three writers and three separate locks (no real synchronization between them can occur).

If you change the show method to static, the writers will synchronize on the Writer class instead - this way all the writers will share the lock and be synchronized with each other.