In my opinion, the answer on the practical exams is correct. In this code, you are executing two threads that have access to the same static variable identifier. Static variables are stored on the heap in java, not on the stack. The execution order of runnables is unpredictable.
However, to change the id value of each thread:
- makes a local copy of the value stored in the id memory address in the CPU registry;
- performs operation
1 - id . Strictly speaking, two operations are performed here (-id and +1) ; - returns the result back to the
id memory on the heap.
This means that although the id value can be changed simultaneously by one of the two threads, only the start and end values ββare mutable. Intermediate values ββwill not be changed by each other.
Moreover, code analysis can show that at any given time id can only be 0 or 1.
Evidence:
Initial value id = 1; One thread will change it to 0 ( id = 1 - id ). And another thread will return it to 1.
Initial value id = 0; One thread will change it to 1 ( id = 1 - id ). And another thread will return it to 0.
Therefore, the state of the id value is discrete either 0 or 1.
The end of the proof.
There can be two possibilities for this code:
Opportunity 1. In a stream, one first accesses the variable identifier. Then the id value ( id = 1 - id will change to 0. After this, only the pick () method will be executed by printing PQ . The second stream will evaluate id at this time id = 0 , then the release() method will print R S. As a result, PQRS will be printed.
Opportunity 2. In a stream, two first access the variable identifier. Then the id value ( id = 1 - id will change to 0. After this, only the pick () method will be executed by printing PQ . In the first case, the identifier will be evaluated at that time id = 0 ; then the release() method will print R S. As a result, PQRS will be printed.
There are no other possibilities. However, it should be noted that PQRS variants, such as PRQS or RPQS , etc., can be printed due to the fact that pick() is a static method and therefore is split between two streams. This leads to the simultaneous execution of this method, which can lead to printing letters in a different order depending on your platform.
However, in any case, the two pick() or release () methods will never be executed, since they are mutually exclusive . Therefore, PQPQ will not be output.
user2399800 Nov 27 '14 at 21:43 2014-11-27 21:43
source share