#166 Method Synchronization with Two Threads
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
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor