简体   繁体   中英

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(). 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. 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. Instead, use isInterrupted() which does not clear the flag!

Also, as chr said, if you start multiple threads (calling listen() multiple times) you will only be able to interrupt the latest one. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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