中断线程以等待用户输入 [英] Interrupt a thread waiting for user input

查看:98
本文介绍了中断线程以等待用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    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上供用户输入,而不会中断.

In this program, the worker thread waiting for the input by the user (which will be an integer value) and sum up until the main thread interrut() it.
But when the main thread interrupt() the worker thread its on I/O for user input and not interrupting.

我想用这个程序得出的输出是:
当程序执行时,用户必须输入整数值并在5秒钟后输入.用户仍在输入值或等待5秒钟关闭时,将打印输入值的总和.结果将在第5秒后立即打印.

The output I want to come up with this program is:
when the program executed, user have to input the integer values and after five sec. the sum of the input values is printed either the user still inputing the values or waiting for 5sec gone off. The result will be printed right after the 5th sec.

推荐答案

确定,因此此代码的问题在于,必须在检查循环条件之前执行语句br.readLine().因此,为避免这种情况,我可能会有3个线程.

OK so the problem with this code is the fact that the statement br.readLine() must be executed before the loop conditional is checked. So to avoid this I would have 3 threads potentially.

线程1:

这将是主线程或父线程.在此线程中,您将只数到5,然后中断线程2.

This would be the main or parent thread. In this thread you will merely count to 5 and then interrupt thread 2.

线程2:

在此线程中,您将监视静态变量:count,然后将其打印并在被中断时中断线程3.

In this thread you will monitor the static variable: count,then print it and interrupt thread 3 when interrupted.

线程3:

在这里,您将获得输入并将输入传递到一个函数中,该函数会将其添加到count中.中断时什么都不做.

Here is were you would get input and and pass the input into a function which would add it to count. When interrupted do nothing.

如果您有任何问题,请告诉我.

If you have any questions let me know.

这篇关于中断线程以等待用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆