0

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.

Doc
  • 10,831
  • 3
  • 39
  • 63

1 Answers1

1

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.

fdreger
  • 12,264
  • 1
  • 36
  • 42
  • Do you know, roughly, how Java synchronization works? I don't know which parts need deeper explaining. – fdreger Jan 04 '17 at 08:37