當用volatile關鍵字聲明變量的時候,就等於告訴虛擬機,這個變量極有可能被某些程序或者線程修改,爲了保證比那輛被修改後應用程序範圍內的全部線程能夠看到這個改動,虛擬機必須採用一些方法保證這個變量的可見性。java
public class PrintString {
private boolean isContinue = true;
public boolean isContinue() {
return isContinue;
}
public void setContinue(boolean aContinue) {
this.isContinue = aContinue;
}
public void printStringFunc(){
try {
while (isContinue){
System.out.println("run printStringFunc threadName=" + Thread.currentThread().getName());
Thread.sleep(1000);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args){
PrintString printString = new PrintString();
printString.printStringFunc();
System.out.println("stop printStringFunc stopThread=" + Thread.currentThread().getName());
printString.setContinue(false);
}
}
複製代碼
run printStringFunc threadName=main
run printStringFunc threadName=main
run printStringFunc threadName=main
run printStringFunc threadName=main
run printStringFunc threadName=main
run printStringFunc threadName=main
run printStringFunc threadName=main
run printStringFunc threadName=main
...
複製代碼
上面的代碼執行後會一直運行沒法停下來,下面來看看解決方法。git
public class PringStringThread {
private boolean isContinue = true;
public boolean isContinue() {
return isContinue;
}
public void setContinue(boolean aContinue) {
this.isContinue = aContinue;
}
public void printStringFunc(){
try {
while (isContinue){
System.out.println("run printStringFunc threadName=" + Thread.currentThread().getName());
Thread.sleep(1000);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
PringStringThread pringStringThread = new PringStringThread();
new Thread(() -> pringStringThread.printStringFunc()).start();
try {
Thread.sleep(2000);
}catch (InterruptedException e){
e.printStackTrace();
}
pringStringThread.setContinue(false);
}
複製代碼
run printStringFunc threadName=Thread-0
run printStringFunc threadName=Thread-0
Process finished with exit code 0
複製代碼
能夠發現線程退出循環了。github
本節代碼Githubbash
歡迎關注公衆號: 微信