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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Do you know, roughly, how Java synchronization works? I don't know which parts need deeper explaining.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.