Two synchronized methods on the same object cannot run at the same time on different threads, because they contend for the same intrinsic lock. That is why 4000 increments split across two threads never lose an update.
class Counter {
private int count = 0;
synchronized void increment() { count++; }
synchronized int get() { return count; }
}
Counter counter = new Counter();
Runnable task = () -> { for (int i = 0; i < 2000; i++) counter.increment(); };
Thread t1 = new Thread(task);
Thread t2 = new Thread(task);
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count: " + counter.get());
Final count: 4000
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27