Java OCA OCP Practice Question 2195

Question

Given the following program, which code modifications will result in both threads being able to participate in printing one smiley ( :-)) per line continuously?

public class Main extends Thread {

  public void run() {                      // (1)
    while(true) {                          // (2)
       try {                               // (3)
           System.out.print(":");          // (4)
           sleep(100);                     // (5)
           System.out.print("-");          // (6)
           sleep(100);                     // (7)
           System.out.println(")");        // (8)
           sleep(100);                     // (9)
       } catch (InterruptedException e) {
         e.printStackTrace();//from   w  w w . j  av  a2s. c  o  m
       }
     }
   }

   public static void main(String[] args) {
     new Main().start();
     new Main().start();
   }
 }

Select the two correct answers.

  • (a) Synchronize the run() method with the keyword synchronized, (1).
  • (b) Synchronize the while loop with a synchronized(Main.class) block, (2).
  • (c) Synchronize the try-catch construct with a synchronized(Main.class) block, (3).
  • (d) Synchronize the statements (4) to (9) with one synchronized(Main.class) block.
  • (e) Synchronize each statement (4), (6), and (8) individually with a synchronized (Main.class) block.
  • (f) None of the above will give the desired result.


(c) and (d)

Note

First note that a call to sleep() does not release the lock on the Main.

class object once a thread has acquired this lock.

Even if a thread sleeps, it does not release any locks it might possess.

(a) does not work, as run() is not called directly by the client code.

(b) does not work, as the infinite while loop becomes the critical region and the lock will never be released.

Once a thread has the lock, other threads cannot participate in printing smiley faces.

(c) works, as the lock will be released between each iteration, giving other threads the chance to acquire the lock and print smiley faces.

(d) works for the same reason as (c), since the three print statements will be executed as one atomic operation.

(e) may not work, as the three print statements may not be executed as one atomic operation, since the lock will be released after each print statement.

Synchronizing on this does not help, as the printout from each of the three print statements executed by each thread can be interspersed.




PreviousNext

Related