0
以下工作示例每3秒打印1到20之間的整數。如果兩個狀態flacs(t1.getStatus,t2.getStatus)中的一個爲真,程序應該終止。如果t1.getStatus
爲真,那麼程序仍在運行,因爲掃描程序沒有終止。中斷掃描程序依賴於其他線程
public class Test {
public static void main(String[] args) {
FirstTask t1 = new FirstTask();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(t1, 0, 3, TimeUnit.SECONDS);
ParallelScanner t2 = new ParallelScanner();
Thread scan = new Thread(t2);
scan.start();
while(true){
if(t1.getStatus() || t2.getStatus()) break;
}
scan.interrupt();
executor.shutdown();
}
}
class ParallelScanner implements Runnable {
private volatile boolean status=false;
public void run() {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
System.out.println("scanner stoped");
scan.close();
this.status=true;
}
public boolean getStatus(){
return this.status;
}
}
class FirstTask implements Runnable {
private volatile boolean status=false;
public void run() {
this.status = status();
}
private boolean status() {
int incident = (int) ((Math.random()*20)+1);
System.out.println(incident);
return incident < 7 ? true : false;
}
public boolean getStatus() {
return this.status;
}
}
要通過狀態控制中斷flac也可能是錯誤的劃痕。我還發現了一個類似的問題here。直到現在,第一個答案並沒有抓住我。第二個答案是錯誤的。有人能提供一個關於這種方法的小例子嗎?有其他的選擇嗎?
Thx爲關鍵字volatile。我重新安排了代碼,希望能夠讓我的問題更容易理解,因爲問題依然存在。它每隔3秒打印1到20之間的數字。這由執行者完成。掃描儀被包裹在一個單獨的線程中。但是,如果't1.getStatus'現在成立,程序不會終止,儘管無限循環中斷。因爲掃描儀正在等待輸入。 –