我正在自己學習 Java 中的多執行緒和并發。請幫助我理解這段代碼。我正在創建一個帶有 'stop' 布爾變數的執行緒,'run' 方法不斷回圈,直到主執行緒在休眠兩秒鐘后將停止變數設定為 true。但是,我觀察到此代碼在無限回圈中運行。我在這里做錯了什么?
public class Driver {
public static void main(String[] args) {
ThreadWithStop threadWithStop = new ThreadWithStop();
Thread thread = new Thread(threadWithStop);
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadWithStop.stopThread();
}
}
class ThreadWithStop implements Runnable {
private boolean stop;
public ThreadWithStop() {
this.stop = false;
}
public void stopThread() {
this.stop = true;
}
public boolean shouldRun() {
return !this.stop;
}
@Override
public void run() {
long count = 0L;
while (shouldRun()) {
count ;
}
System.out.println(count "Done!");
}
}
uj5u.com熱心網友回復:
好吧,不能保證停止,但可能會停止。您stop通過stopThread()從主執行緒呼叫對所做的更改不能保證對可見,ThreadWithStop直到您以某種方式與它同步。
實作此目的的一種方法是使用synchronized關鍵字保護對變數的訪問- 例如,請參閱有關同步方法的官方 Oracle 教程:
通過以下更改,stop可以保證更改為可見。
class ThreadWithStop implements Runnable {
private boolean stop;
public ThreadWithStop() {
this.stop = false;
}
public synchronized void stopThread() {
this.stop = true;
}
public synchronized boolean shouldRun() {
return !this.stop;
}
@Override
public void run() {
long count = 0L;
while (shouldRun()) {
count ;
}
System.out.println(count "Done!");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/327034.html
上一篇:這是升級標準庫鎖的有效方法嗎?
下一篇:這是升級標準庫鎖的有效方法嗎?
