并发编程中3个特性需要关注(原子性,可见性,有序性)
1.原子性(不支持)
public class TestAtom {
//并发编程:需要关注三个特性:原子性、可见性、有序性
//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 最后输出不会是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,上面线程会打印“in”
System.out.println("change success");
}
}).start();
}
}
3.有序性(禁止重排序):经典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;
}
}