2017-02-18 33 views
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。直到現在,第一個答案並沒有抓住我。第二個答案是錯誤的。有人能提供一個關於這種方法的小例子嗎?有其他的選擇嗎?

回答

0

我猜你知道你的FirstTask只運行一次,所以沒關係。

你需要讓你的狀態變量volatile讓它從每個線程的ram中讀取,否則你會得到一個不確定的行爲。

爲什麼你沒有使用掃描儀的循環?我不知道Scanner類的具體細節,沒有更多數據時是否引發異常,或者由於我的代碼假定返回null?

for(;;){ 
    String input = scan.nextLine(); 
    if(input == null) 
     break; 
    // Assuming that by jump over (run through) you mean: 
    // ignore the line that comes from the scanner 
    if(!t1.getStatus()){ 
     System.out.println(input); 
    } 
} 

還您getStatus()方法需要將狀態恢復到true或者它也將忽略(=不打印)所有連續的線。

+0

Thx爲關鍵字volatile。我重新安排了代碼,希望能夠讓我的問題更容易理解,因爲問題依然存在。它每隔3秒打印1到20之間的數字。這由執行者完成。掃描儀被包裹在一個單獨的線程中。但是,如果't1.getStatus'現在成立,程序不會終止,儘管無限循環中斷。因爲掃描儀正在等待輸入。 –