PackageCom.chzhao; Public classVolatiletestextendsThread {Private Static intCount = 0; Public voidRun () {count++; } Public Static voidMain (string[] args) {Thread threads[]=Newthread[10000]; for(inti = 0; i < threads.length; i++) {Threads[i]=Newvolatiletest (); } for(inti = 0; i < threads.length; i++) {Threads[i].start (); } Try{Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (count); }}
The code above, expecting the output is 10000, then, because count++ is not thread-safe, so the output is often less than 10000.
To solve this problem, the volatile keyword was added.
PackageCom.chzhao; Public classVolatiletestextendsThread {Private volatile Static intCount = 0; Public voidRun () {count++; } Public Static voidMain (string[] args) {Thread threads[]=Newthread[10000]; for(inti = 0; i < threads.length; i++) {Threads[i]=Newvolatiletest (); } for(inti = 0; i < threads.length; i++) {Threads[i].start (); } Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (count); }}
After modification, a value other than 10000 is often output.
Modified to synchronized form, the code is as follows:
PackageCom.chzhao; Public classSynchronizedtestextendsThread {Private Static intCount = 0; Public voidrun () {synchronized(lockclass.lock) {count++; } } Public Static voidMain (string[] args) {Thread threads[]=Newthread[10000]; for(inti = 0; i < threads.length; i++) {Threads[i]=Newsynchronizedtest (); } for(inti = 0; i < threads.length; i++) {Threads[i].start (); } Try{Thread.Sleep (2000); } Catch(interruptedexception e) {e.printstacktrace (); } System.out.println (count); }}
Package Com.chzhao; Public class Lockclass { publicstaticbytenewbyte[0];}
After this modification, the output is 10000.
Does this mean that the keyword "volatile" is completely useless? Only synchronized can guarantee thread safety?
In the Java theory and Practice: Correct use of Volatile variables, it is mentioned that:
The Java™ language contains two intrinsic synchronization mechanisms: synchronous blocks (or methods) and volatile variables. Both of these mechanisms are proposed to achieve the security of code threads. Where volatile variables are less synchronous (but sometimes simpler and less expensive), and their use is more error-prone. Volatile variables in the Java language can be thought of as "light", and synchronized
synchronized
volatile variables require less coding and run-time overhead than blocks, but only part of the functionality that they can implement synchronized
.
That is to say, in some cases, volitile is more convenient than synchronized, and of course, synchronization is even more nearly.
See "Java Theory and Practice: using Volatile variables correctly"
Reference:
Http://www.ibm.com/developerworks/cn/java/j-jtp06197.html
Volatile and synchronized in Java Multi-threading