Java OCA OCP Practice Question 2953

Question

Given:

public class Main extends Thread {
   int x = 0;//from w ww. j ava2s  .  c  om

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

   public void run() {
      for (int j = 0; j < 3; j++) {
         x = x + 1;
         x = x + 10;
         System.out.println(x + " ");
         x = x + 100;
      }
   }
}

If the code compiles, which value(s) could appear in the output? (Choose all that apply.)

  • A. 12
  • B. 22
  • C. 122
  • D. 233
  • E. 244
  • F. 566
  • G. Compilation fails.


A, B, C, D, E, and F are all correct.

Note

The variable x is "shared" by both threads, and collectively the two threads will iterate through the for loop six times.

Remember that either thread can pause any number of times, and at any point within the run() method.

G is incorrect based on the above.




PreviousNext

Related