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:你说得对。你有任何解决方案? –