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秒後立即打印。
我相信你的問題是br.readLine()將在循環的布爾值被重新評估之前執行。這意味着你必須在循環過期後輸入1個數字 – jozefg
@jozefg:你說得對。你有任何解決方案? –