The following is an example of a total atomicity implementation by using volatile:
The final result of the variable number is calculated by creating 100 threads.
Packagecom. sychronized; Public classVolatiledemo {Private volatileintNumber=0; Public intGetNumber () {return This. number; } Public voidIncrease () { This. number++; } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub FinalVolatiledemo voldemo=NewVolatiledemo (); for(inti=0;i<100;i++) { New Thread (new Runnable () {@Override public void Run () {voldemo.increase (); }}). Start (); } //If there are child threads running, the main thread will let the CPU resources//The main thread continues to execute until all the child threads have run out while(Thread.activecount () >1) {Thread.yield (); } System.out.println ("Number:" +Voldemo.getnumber ()); }}
Operation Result:
Several results were found:
The reason for this result is that the volatile keyword has visibility, and number++ actually has three steps, but not atomicity.
Java thread-volatile does not guarantee atomicity