1.線程安全 |
- 線程安全是多線程編程時的計算機程序代碼中的一個概念。在擁有共享數據的多條線程並行執行的程序中,線程安全的代碼會通過同步機制保證各個線程都可以正常且正確的執行,不會出現數據污染等意外情況
2.怎麼保證線程安全 |
-
使用關鍵字
-
volatile
- 可見性
- 禁止指令重排
-
代碼
-
//可見性
import java.util.concurrent.TimeUnit;
public class volatileTest implements Runnable{
volatile boolean running = true;
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println("myThread start...");
while(running){
//doSomething();
}
System.out.println("myThread end...");
}
public static void main(String[] args) {
volatileTest vt = new volatileTest();
new Thread(vt).start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
vt.running = false;
}
}
//禁止指令重排
public class DoubleCheckedLocking { // 1
private volatile static Instance instance; // 2
public static Instance getInstance() { // 3
if (null == instance) { // 4:第一次檢查
synchronized (DoubleCheckedLocking.class) { // 5:加鎖
if (instance == null) // 6:第二次檢查
instance = new Instance(); // 7:問題的根源出在這裏
} // 8
} // 9
return instance; // 10
} // 11
}
//volatile不保證原子性,可以使用原子引用解決原子性問題
Public static void main(string[] args){
User z3=new User("z3",33);
User l4=new User("l4",43);
AtomicReference<User> atomicReference = new AtomicReference<>();
atomicReference.set(23);
System.out.println(atomicReference.compareAndSet(z3,l4)+\t+atomicReference.get().toString());
}
-
Synchronized
- 代碼
public class SingletonDemo{
private static SingletonDemo instance=null;
private SingletonDemo(){
System.out.pringtln();
}
//使用雙端檢鎖機制(Double check Lock(DLK))
public static SingletonDemo getInstance(){
if(instance == null){
synchronized(SingletonDemo.class){
if(instance == null){
instance = new SingletonDemo();
}
}
}
return instance;
}
}