2012-01-25 28 views
1
public class InterruptedInput { 

    public static void main(String[] args) { 
     InputThread th=new InputThread(); //worker thread instantiated. 
     th.start(); //worker thread start. 
     try{ 
      Thread.sleep(5000); //main thread sleep for 5 sec. 
     }catch(InterruptedException ex){} 
     th.interrupt(); //worker thread interrupted. 
    } 
} 

class InputThread extends Thread{ 
    int sum; 
    BufferedReader br; 
    public void run(){ 
     br=new BufferedReader(new InputStreamReader(System.in)); 
     try{ 
      sum(); 
      sleep(10000); //worker thread sleep for 10 sec. 
     }catch(Exception ex){ 
      System.out.println("sum="+sum); 
     } 
    } 

    public void sum(){ 
     try{ 
      while(!isInterrupted()){ 
       sum+=Integer.parseInt(br.readLine()); 
      } 
     }catch(Exception ex){} 
    } 
} 

在這個程序中,工作線程等待由用戶(這將是一個整數值),輸入和總結,直到主線程interrut()它。
但是當主線程interrupt()worker thread其對I/O的用戶輸入和不中斷。中斷一個線程等待用戶輸入

我想要這個程序的輸出是:
當程序執行時,用戶必須輸入整數值,並在5秒後。輸入值的總和將被打印,或者用戶仍然輸入值或等待5秒後消失。結果將在第5秒後立即打印。

+1

我相信你的問題是br.readLine()將在循環的布爾值被重新評估之前執行。這意味着你必須在循環過期後輸入1個數字 – jozefg

+0

@jozefg:你說得對。你有任何解決方案? –

回答

1

好,所以這個代碼的問題是在檢查循環條件之前必須執行語句br.readLine()。所以爲了避免這種情況,我可能會有3個線程。

主題1:

這將是主線或父線程。在這個主題,你會僅僅數到5,然後中斷線程2

線程2:

在這個線程要監視靜態變量:count,然後打印和中斷時中斷線程3。

主題3:

這裏是你會得到輸入和輸入傳遞到這將它添加到count功能。中斷時什麼也不做。

如果您有任何問題,請告訴我。

1

由於IO是非可中斷可以@Override的InputThread關閉輸入流

@Override 
public void interrupt(){ 
    try{ 
     this.br.close(); 
    }finally{ 
     super.interrupt(); 
    } 
} 
+0

輸出不像它應該的那樣。請檢查上面的代碼。 –

+0

你不應該在sum()方法中捕獲併吞下IOException。刪除該try/catch並用方法聲明傳播Exception inline。 –

+0

@John Vint:我在我的(現在已刪除的)答案中遵循了同樣的直覺,即從主線程異步關閉BufferedReader並導致IOException,但由於某種原因,它似乎無法工作。 br.close()的調用會無限期地阻塞。 – Tudor

0

另一種方法是,以允許在任何時間將被打印的計數。添加以下到InputThread類:

private AtomicInt count; 

public int getCount() { 
    return count; 
} 

而且具有的主要方法打印計數:

System.out.println("Sum:" + th.getCount()); 

這將避免任何需要interupting線程。

+0

對不起!但我需要它使用'interrupt()' –