[英]Two threads using same variable
private void stopThread() {
thread1.canRun(false);
}
private void createThread() {
thread1.stopThread();
thread1.canRun(true);
thread1 = new Thread(thread1);
t.start();
}
我只有一個按鈕。 當我單擊按鈕時,我執行的線程數將為n,而當我再次單擊按鈕時,最后一個線程應停止並創建一個新線程。
問題是當我創建第二個線程時,似乎最后一個並沒有停止並且都繼續運行
@Override
public void run() {
try {
for (int i = 0; i <= TimeOut && canRun; i++) {
System.out.println(i);
Thread.sleep(1000);
}
}
private volatile boolean canRun;
問題可能出在以下幾行:
thread1.stopThread(); // <-- sets canRun to false
thread1.canRun(true); // <-- sets canRun to back to true
您還可以使用true初始化canRun
,這意味着線程可以在其初始狀態下運行:
private volatile boolean canRun = true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.