In the study of the visibility of volatile semantics and the test of restraining order reordering, it is found that the feature of forbidden command reordering is not shown.
The experiment code is as follows
Packagecom.aaron.beginner.multithread.volatiletest;ImportJava.util.concurrent.CountDownLatch;/** * @author* @description A word describing the purpose of the document * @date 2017-03-01*/ Public classvolatileandnonvolatiletest{Private volatile BooleanFlag; Private intnum; Public Static voidMain (string[] args)throwsinterruptedexception { for(inti = 0; I < 5000; i++) { FinalVolatileandnonvolatiletest test =Newvolatileandnonvolatiletest (); Countdownlatch latch=NewCountdownlatch (2); Thread Write=NewThread ((){test.write (); Latch.countdown (); }); Thread Read=NewThread ((){test.read (); Latch.countdown (); }); Write.start (); Read.start (); Latch.await (); } } Private voidRead () {if(flag) {System.out.println ("=" + num *num); } } Private voidwrite () {num= 10;//step 1 flag=true;//Step 2}}
Experimental steps:
Pay attention to the flag variables in the code and test the output of the flag variable with volatile and no volatile modifiers, respectively.
The main features of this test code are:
- The Write method is responsible for modifying the NUM variable, setting flag=true after modification, indicating that the NUM variable has been modified successfully
- The Read method is responsible for reading the modified NUM value and entering the square
Experimental steps:
- Each time two threads are started in the loop, one thread is responsible for invoking the write modification data, and the other thread is responsible for reading the modified values
- Observing the experimental structure
Expected Result:
- When flag does not have a volatile modifier, we should have expected to be able to output "=100"
- When flag has a volatile modifier, because of the visibility and prohibition of order reordering, each time the normal output of "=100"
Actual results:
- When flag does not have a volatile modifier, multiple experiments do not find that the command reordering occurs (that is, "=0" occurs, which means that steps 1 and 2 in the Write method do not have a reorder ( Step 2 takes place before Step 1 ))
- When flag has a volatile modifier (in theory there is visibility and no order reordering, no "=0"), no "= 0" is actually present, and 1 results are consistent.
That is, the result of adding and not adding volatile is consistent.
Ask the great God, do you know how to test this volatile, embodies the prohibition of order reordering characteristics and visibility characteristics?
Doubts about the visibility of volatile and the reordering of forbidden commands