简体   繁体   English

用于中断进程的Java中断线程

[英]Interrupting Thread in Java for hanged process

If i have a thread something like this: 如果我有这样的线程:

Thread t = new Thread(myThread);
t.start();

private static Runnable myThread = new Runnable() {
    public void run() {
        try{
            String line=null;
            while ((line = eStream.readLine()) != null){
                //do something
            }
         }
         catch (Exception e){}
    }
};  

Now what happens in while loop, at times the readLine() is hanged because it is expecting input from external process. 现在while循环中发生了什么,有时readLine()被挂起,因为它期望来自外部进程的输入。 So in that case what i am trying to do is to setup a timer and if it expires, i interrupt this thread t with t.interrupt(); 所以在这种情况下,我要做的是设置一个计时器,如果它到期,我用t.interrupt(); interrupt this thread t t.interrupt();

Now when i try to catch InterruptedException after the try block, i am getting compile time error. 现在当我尝试在try块之后捕获InterruptedException ,我收到编译时错误。 Can someone tell me in this scenario, how can i catch Interrupted Exception? 在这种情况下有人能告诉我,我怎样才能捕获中断异常?

Thank you 谢谢

interrupt won't free a blocking readLine() call. 中断不会释放阻塞的readLine()调用。 You have to close the stream to do that. 你必须关闭流才能做到这一点。

You are catching the InterruptedException already (and ignoring it) with this line 您正在使用此行捕获InterruptedException(并忽略它)

catch (Exception e){}

This won't work 这不行

line = eStream.readLine().toString()

As it will throw a NullPointerException when you reach the end of file. 因为当你到达文件末尾时会抛出NullPointerException。 Remove the .toString() 删除.toString()

From the doc for InterruptedException : 来自InterruptedException的doc:

Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread interrupts it using the interrupt method in class Thread. 当线程等待,休眠或以其他方式暂停很长一段时间时抛出,另一个线程使用Thread类中的interrupt方法中断它。

I suspect what you're interested in is InterruptedIOException : 我怀疑你感兴趣的是InterruptedIOException

Signals that an I/O operation has been interrupted. 表示I / O操作已中断。 An InterruptedIOException is thrown to indicate that an input or output transfer has been terminated because the thread performing it was interrupted. 抛出InterruptedIOException以指示输入或输出传输已终止,因为执行它的线程已中断。

I would check out this JavaSpecialists newsletter on cleanly shuttin gdown threads and particularly the subsection What about threads blocked on IO? 我会查看关于干净关闭的gdown线程的JavaSpecialists新闻简报 ,特别是关于在IO上阻塞的线程怎么办? which covers this area in some detail. 它详细介绍了这个领域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM