One, as a switch
A. Atomicboolean
Private Atomicboolean update = new Atomicboolean (false);
public void init ()
{
if (This.update.compareAndSet (False, True))
{
try{
//Do some thing
}
finally{
This.refresh.set (false);
}
}
B. Volatile
Public volatile Boolean update = FALSE;
public void init ()
{
if (update = = False) {
update = true;
DP some thing
}
}
Second, counter
A.atomicinteger
private static Atomicinteger a = new Atomicinteger (0);
A.getandincrement ();
b.sychrognized + volatile
private volatile int value;
public int GetValue () {return value;}
public synchronized int increment () {return
value++;
}
question: Here the volatile keyword to remove what will be different?
Answer: No, remove the time, multithreading, other threads will read the value cached in the Register
Third, with lock
Private lock lock = new Reentrantlock ();
public void M1 () {
this.lock.lock ();
try{
//do Some thing
}finally{
lock.unlock ();
}