简体   繁体   English

Java线程执行然后被多次中断

[英]Java threads executing then being interupted multiple times

I am having a strange issue where I have a thread being used to listen for incoming messages on a socket. 我有一个奇怪的问题,我有一个线程用于侦听套接字上的传入消息。 The thread is declared globally but instantiated inside method listen(). 该线程是全局声明的,但在方法listen()中实例化。 This allows me to interrupt it from another method stopListen() which works perfectly the first time, however when listen() and stopListen() are called a second time it does not appear to get interrupted. 这使我可以从另一个方法stopListen()中断它,该方法在第一次运行时效果很好,但是,当第二次调用listen()和stopListen()时,它似乎没有被中断。 The code commented as "Do some stuff" still executes after waiting for the incoming message the second time. 注释为“做一些事情”的代码在第二次等待传入消息后仍然执行。 Below is a cut down version of the code. 下面是该代码的简化版本。

public class Con {
    private Thread listen;

    public void listen() {
        listen = new Thread(new Runnable() {
            @Override
            public void run() {
                while (!Thread.interrupted()) {
                    //Wait for an incoming message
                    if (!Thread.interrupted()){
                        //Do some stuff
                    }
                }
            }
        });
        listen.start();
    }

    public void stopListen() {
        listen.interrupt();
    }
}

I understand its a bit weird having a variable and a method called the same thing. 我知道有一个变量和一个叫做同一件事的方法有点奇怪。 Should this work or can I not interrupt threads by using a global variable more than once? 这应该可行吗,还是我不能多次使用全局变量来中断线程?

Thanks. 谢谢。

The main problem I see is that interrupted() will reset the interrupt-flag (see linked doc), meaning the next call to interrupted() will return false unless it has been interrupted again. 我看到的主要问题是, interrupted()会重置中断标志(请参阅链接的文档),这意味着下一次对interrupted()调用将返回false,除非再次被中断。 Instead, use isInterrupted() which does not clear the flag! 而是使用isInterrupted()不会清除标志!

Also, as chr said, if you start multiple threads (calling listen() multiple times) you will only be able to interrupt the latest one. 另外,正如chr所说,如果您启动多个线程(多次调用listen() ),您将只能中断最新的线程。 In that case, make a List of Threads and interrupt them all (or only the first one in the list and remove it from the list, or whatever functionality you want). 在这种情况下,请创建一个线程List并将其全部中断(或仅中断List中的第一个线程,然后将其从列表中删除,或使用任何所需的功能)。

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

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