简体   繁体   中英

OCJP Dumps Thread

Can anyone help me to solve the following problem?

public class Starter extends Thread{
   private int x=2;
   public static void main(String[] args) throws Exception{
      new Starter().makeItSo();
   }
   public Starter(){
      x=5;
      start(); 
   }
   public void makeItSo() throws Exception {
      join();
      x=x-1;
      System.out.println(x);
   }
   public void run(){x*=2;}
}

A. 4

B. 5

C. 8

D. 9

E. Compilation failure

F. An exception is thrown at runtime

G. It is impossible to determine for certain

In the dump the answer is D. I know that a new thread is created in new Starter().makeItSo. But can anyone tell me why the x*=2 in run() execute between x=x-1 and System.out.println(x) in method makeItSo?

But can anyone tell me why the x*=2 in run() execute between x=x-1 and System.out.println(x) in method makeItSo

That's not what happens. Here's an explanation of what happens in the posted code:

1) The main thread creates a new object of type Starter, initializing its instance variable x first to 2 (the variable initialization) and then (in the constructor) setting the same instance variable to 5, and starting the new thread.

2) The main thread calls the method makeItSo (on the Starter instance created by the constructor call) and joins on the new thread, waiting until it finishes.

3) The new thread executes its run method, doubling x, and finishes (notifying the main thread that it's done).

4) The main thread then wakes up, subtracts 1 from x, and prints 9.

Since x is modified across threads and isn't volatile or atomic and no synchronization is performed, it's not obvious that the updates to x by the new thread are guaranteed to be made visible to the main thread (so whether it works on purpose or by accident is unclear), making G look like the right answer. But join does synchronization on the new thread (since join is implemented using wait, locking on the thread); the current value of x will be visible by the time the main thread returns from the join call. So the answer is D.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM