多线程中 volatile 保证可见性和不保证原子性,代码说明问题
例1:原子性问题
/**
* 不能保证原子性
*/
public class VolatileUnsafe2 {
private volatile long count =0;
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
//count进行累加
public void incCount(){
count++;
}
//线程
private static class Count extends Thread{
private VolatileUnsafe2 simplOper;
public Count(VolatileUnsafe2 simplOper) {
this.simplOper = simplOper;
}
@Override
public void run() {
for(int i=0;i<10000;i++){
simplOper.incCount();
}
}
}
public static void main(String[] args) throws InterruptedException {
VolatileUnsafe2 simplOper = new VolatileUnsafe2();
//启动两个线程
Count count1 = new Count(simplOper);
Count count2 = new Count(simplOper);
count1.start();
count2.start();
Thread.sleep(50);
System.out.println(simplOper.count);//20000?
}
}
例2:可见性问题
/**
* 可见性
*/
public class VolatileVisible {
public static int count = 1;
private volatile static boolean ready;//说明,这里将volatile去掉后,将陷入无限循环,是因为子线程看不到ready已经修改
public static class ThreadT1 implements Runnable {
@Override
public void run() {
System.out.println("run ...");
while (!ready) ;//无限循环
System.out.println("end"+count);
}
}
public static void main(String[] args) throws InterruptedException {
new Thread(new ThreadT1()).start();
Thread.sleep(200);
count = 20;
ready = true;
Thread.sleep(200);
System.out.println("main end");
}
}