Multiple choice technology programming languages

class PingPong2 { synchronized void hit(long n) { for(int i = 1; i < 3; i++) System.out.print(n + "-" + i + " "); } } public class Tester implements Runnable { static PingPong2 pp2 = new PingPong2(); public static void main(String[] args) { new Thread(new Tester()).start(); new Thread(new Tester()).start(); } public void run() { pp2.hit(Thread.currentThread().getId()); } } Which statement is true?

  1. The output could be 8-1 7-2 8-2 7-1

  2. The output could be 6-1 6-2 5-1 5-2

  3. The output could be 6-1 5-2 6-2 5-1

  4. The output could be 6-1 6-2 5-1 7-1

Reveal answer Fill a bubble to check yourself
B Correct answer
Explanation

The synchronized keyword on the hit() method ensures that once one thread enters this method, other threads must wait for it to complete before entering. Each thread calls hit() with its unique thread ID, and within hit() the loop prints 'threadId-iteration' twice. Because of synchronization, one thread completes both iterations (6-1 6-2 or 5-1 5-2) before the next thread begins. Option B correctly shows this atomic behavior - all of one thread's output, then all of the other's.