#166 Method Synchronization with Two Threads

Companies:
Opensolutions
Themes:
JavaConcurrencyCode Review

What will be printed to the screen?

public class ThreadDemo {

    private int count = 1;

    public synchronized void doSomething() {
        for (int i = 0; i < 10; i++) {
            System.out.println(count++);
        }
    }

    public static void main(String[] args) {
        ThreadDemo demo = new ThreadDemo();
        Thread a1 = new A(demo);
        Thread a2 = new A(demo);
        a1.start();
        a2.start();
    }
}

class A extends Thread {
    ThreadDemo demo;

    public A(ThreadDemo td) {
        demo = td;
    }

    public void run() {
        demo.doSomething();
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in