Sample31 is run - what will be the output?
public class Sample31
{
static class Counter { int value; synchronized void bump() { value++; } }
public static void main(String[] args) throws InterruptedException
{
Counter one = new Counter(), two = new Counter();
Thread a = new Thread(() -> { for (int i = 0; i < 5; i++) one.bump(); });
Thread b = new Thread(() -> { for (int i = 0; i < 5; i++) two.bump(); });
a.start(); b.start(); a.join(); b.join();
System.out.println(one.value + " " + two.value);
}
}
Answer: C
Each thread increments its own Counter, so there is no shared state and no contention at all; the two synchronized methods lock different instances, which does not matter here. Each loop runs five times, so both fields end at 5 and the joins make that visible to main.
Please log in or register to report this question.