总结:volatile 关键字,使一个变量在多个线程间可见
volatile不能替代synchronized
synchronized可以保证可见性和原子性,volatile只能保证可见性
原理比较复杂,需要了解java内存模型JMM
參考:http://www.cnblogs.com/nexiyi/p/java_memory_model_and_thread.html
http://blog.csdn.net/guyuealian/article/details/52525724
package com.victor.thread;
/**
* volatile 关键字,使一个变量在多个线程间可见 volatile并不能保证多个线程共同修改running变量时所带来的不一致问题,
* 也就是说volatile不能替代synchronized synchronized可以保证可见性和原子性,volatile只能保证可见性
*
* 原理比较复杂,需要了解java内存模型JMM
*
* @author Victor
*/
public class VolatileThread_010 extends Thread {
// 不加volatile 程序会出现死循环
private volatile boolean running;
public void run() {
System.out.println("m start");
while (!running) {
}
System.out.println("m end!");
}
public void stopIt() {
running = true;
}
public boolean getStop() {
return running;
}
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
VolatileThread_010 a = new VolatileThread_010();
a.start();
Thread.sleep(1000);
a.stopIt();
Thread.sleep(2000);
System.out.println("finish main");
System.out.println(a.getStop());
}
}