Questions about volatile visibility and disallow Command Re-sorting, volatile sorting
In the test of learning volatile semantics visibility and prohibiting Command Re-sorting, it is found that the feature of prohibiting Command Re-sorting cannot be reflected.
The experiment code is as follows:
Package com. aaron. beginner. multithread. volatiletest; import java. util. concurrent. countDownLatch;/*** @ author * @ description describes the object's purpose in one sentence * @ date */public class VolatileAndNonVolatileTest {privateVolatileBoolean flag; private int num; public static void main (String [] args) throws InterruptedException {for (int I = 0; I <5000; I ++) {final VolatileAndNonVolatileTest test = new VolatileAndNonVolatileTest (); CountDownLatch latch = new CountDownLatch (2); Thread write = new Thread ()-> {test. write (); latch. countDown () ;}); Thread read = new Thread ()-> {test. read (); latch. countDown () ;}); write. start (); read. start (); latch. await () ;}} private void read () {if (flag) {System. out. println ("=" + num * num) ;}} private void write () {num = 10; // Step 1 flag = true; // Step 2 }}
Tutorial steps:
Pay attention to the flag variables in the Code and test the output of the flags with volatile modification and without volatile modification respectively.
Main functions of this test code:
Tutorial steps:
Expected results:
Actual results:
That is, the result is consistent with that without volatile.
Do you know how to test this volatile, which demonstrates the features and visibility of prohibiting Command Re-sorting?