1, through the Synchronized keyword to achieve, all add synchronized and block statements, in multi-threaded access, at the same time only one thread can use
Synchronized a modified method or block of code.
2, with the volatile modified variable, the thread every time using the variable, will read the variable after the last value modified.
Multithreading in Java in-memory access: Each thread has a line stacks, when used this thread, first access to the stack and then there is the object to find the variables in the heap, to extract, and to load. Write back to the heap each time the change is made, so that the data in the heap is the most recent value, and other threads use these shared variables to get the final value.
The following is the interaction of Java thread Memory:
If another thread runs out of the variable value of 2 and then saves it in memory, the next thread is loaded again to get the value of the variable in memory is 2, so get the final value.
Note: Volatile can only say is to change the value of n can not be changed by himself, for example: n++ is wrong, will not play a role, but n=m++; this is possible, so volatile effective, this is the original level. In general, the keyword synchronized is used to synchronize, which means that only one thread at a time is executing. The result of this is what we want.
Here is an example:
Package volatile1;
/**
* Created by the Administrator on 2015/11/3 0003.
* * Public
class Volatile extends thread{
//private Volatile static int n=0;
private static int n=0;
public static synchronized Void Inc () {
n++
}
public void Run () {for
(int i=0;i<10;i++) {
Inc ()}
}
public static void Main (string[] args) throws interruptedexception {
Thread thread[]=new thread[100];
for (int i=0;i<thread.length;i++) {
thread[i]=new Volatile ();
}
for (int i=0;i<thread.length;i++) {
thread[i].start ();
}
for (int i=0;i<thread.length;i++) {
thread[i].join ();
}
System.out.println ("n=" +VOLATILE.N);
}
Run result is 1000
And with volatile, the operation result is 965,1000 many kinds of situation, so in order to guarantee the atomicity and the reliability I think everybody still uses synchronized better