并發(fā)編程中3個(gè)特性需要關(guān)注(原子性兵睛,可見性鸵赫,有序性)
1.原子性(不支持)
public class TestAtom {
//并發(fā)編程:需要關(guān)注三個(gè)特性:原子性重窟、可見性丹皱、有序性
//volatile無法保證原子性
private static volatile int count = 0;
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 1000; j++) {
count++;
}
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count);
}
}
count 最后輸出不會(huì)是10000。
2.可見性(支持)
public class TestVisible {
//線程間不可見搪哪,使用volatile使可見
private static volatile boolean flag = false;
public static void main(String[] args) throws InterruptedException {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("waiting");
while (!flag) {
}
System.out.println("in");
}
}).start();
Thread.sleep(1000);
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("change flag");
flag = true; //修改flag靡努,上面線程會(huì)打印“in”
System.out.println("change success");
}
}).start();
}
}
3.有序性(禁止重排序):經(jīng)典DCL
public class SingleTon {
//volatile 禁止指令重排序
private static volatile SingleTon singleTon;
private SingleTon() {
}
public static SingleTon getInstance() {
if (null == singleTon) {
synchronized (SingleTon.class) {
if (null == singleTon)
singleTon = new SingleTon();
}
}
return singleTon;
}
}