Home > Back-end >  The volatile keyword didn't work!
The volatile keyword didn't work!

Time:10-07

 public class SimpleVolatile1 {
Static class BossThread {
Public volatile int the age=30;

Public void execBirth () {
Age++;
System. The out. Println (" boss. Age++ ");
}

Public void print () {
While (age & lt; 31) {
System. The out. Println (age);
}
}
}

Public static void main (String [] args) {
BossThread bt=new BossThread ();

for(int i=0; i<10; I++) {
New Thread (bt: : print). The start ();
}
New Thread (bt: : execBirth). The start ();
}
}

One on my computer output is the result of the
 
3030
30
30
Boss. Age++
30
30
30
30
30
30

According to the function of the volatile keyword, when a Shared variables are marked as volatile, it should not appear dirty read phenomenon, but in my test program, boss. After age++ be printed, some threads still read the old value!
Someone can give you explain it!
Thank you very much!

CodePudding user response:

This is the code to handle atomicity,
Assuming the print thread judgment while (age<31) formed into the circulation, just want to perform System. Out. The println (30) (println parameter passing over here, but before printing processing could perform), CPU power is back, turn execBirth thread execution, execBirth after the thread execution, turn the print thread execution, so the print thread will still print 30 (before println (30) parameter is ok, just before printing), so it is that you now as a result,
So, this has nothing to do with volatile, is to deal with the atomicity of code,

CodePudding user response:

Your definition is: public volatile int the age=30; It is not a Shared static variables, each object instance, there is a this variable

You launched 10 instances in the loop, print the 10 to 30, outside of the loop thread execution execBirth, print the boss. Age++, your results will be like, just boss. Age++ in slightly different position before and after the


Define the right way is: the static volatile int the age=30;
  • Related