Two threads acting on the same managed

Given:

public class Thread1 { int x = 0; public class Runner implements Runnable { public void run() { int current = 0; for (int i = 0; i < 4; i++) { current = x; System.out.print(current + " "); x = current + 2; } } } public void go() { Runnable r1 = new Runner(); new Thread(r1).start(); new Thread(r1).start(); } public static void main(String[] args) { new Thread1().go(); } } 

Which of the two possible outcomes? (Choose two)

a. 0, 2, 4, 4, 6, 8, 10, 6,

B. 0, 2, 4, 6, 8, 10, 2, 4,

S. 0, 2, 4, 6, 8, 10, 12, 14,

D. 0, 0, 2, 2, 4, 4, 6, 6, 8, 8, 10, 10, 12, 12, 14, 14,

E. 0, 2, 4, 6, 8, 10, 12, 14, 0, 2, 4, 6, 8, 10, 12, 14,

I chose A and B, but I'm not sure if this is the correct answer.

+4
source share
2 answers

First of all, D. and E. are absent. Since region i local to the function, we know that there will be 8 numbers.

Now

B. 0, 2, 4, 6, 8, 10, 2, 4,

wrong. What for? To print the last two positions, each thread must write the variable x at least two times. At this point, the minimum value for x is 4 . This means that regardless of race conditions, the last two values โ€‹โ€‹must be greater than or equal to 4 .

EDIT C is entirely possible. The lack of synchronization does not mean that it is impossible to have the so-called sequential execution (that is, as if the threads were running one after another). The lesson from concurrency is that you donโ€™t know how threads will alternate

  C. 0, 2, 4, 6, 8, 10, 12, 14, 

happens for example:

  • when the first thread as the time until update x complete before the second run
  • when the first thread is suspended until the first current = x; , the second completion is performed and the first continues.
  • tons of other cases.

As Brian Goetz said:

"Writing the right programs is hard; writing the right parallel programs is harder."

+3
source

Answer: A and C. You can immediately eliminate D and E, because both threads will display 4 results, so 8 results in total, leaving only A, B and C in the game.

B is excluded because the sequence between two 2 is too large to create one thread, so both threads should have done more work than just 2.

0
source

All Articles