关于volatile,公认它的作用是保证可见性,无法保证原子性,对于多个线程的访问还是需要加锁,这是确定的,比如代码示例如下:
public class VolatileTest {
private volatile int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void increAge() {
age++;
}
public static void main(String[] args) throws InterruptedException {
VolatileTest vt = new VolatileTest();
Thread t1 = new Thread(new Worker(vt));
Thread t2 = new Thread(new Worker(vt));
Thread t3 = new Thread(new Worker(vt));
Thread t4 = new Thread(new Worker(vt));
t1.start();t2.start();t3.start();t4.start();
while (true) {
}
}
private static class Worker implements Runnable {
private VolatileTest vt;
public Worker(VolatileTest vt) {
this.vt = vt;
}
@Override
public void run() {
//synchronized(vt) {
System.out.println(Thread.currentThread().getName() + " age is:" + vt.getAge());
vt.increAge();
//}
}
}
}
程序运行结果当然是不确定的,其中某一次的结果为:
Thread-0 age is:0
Thread-2 age is:0
Thread-1 age is:2
Thread-3 age is:3
要保证程序逻辑正确执行,还得需要把注释的synchronized打开才行;那么什么时候可以和需要用volatile呢?我总结有以下几点:
1、首先被volatile修饰的变量大部分是一个标志性变量(比如布尔型),而不是一个integer或者double(这些变量往往需要反复被多线程读写),对这个变量的写入是单线程完成的
2、该变量单独使用,不和其他变量组合在一起形成复合判断条件
大概就是这些,以后再补充