多執行緒總結第四篇之volatile
阿新 • • 發佈:2019-01-05
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());
}
}