Kill a Thread working with flag in Java

168 views Asked by At

I implemented my own Thread in Java this way :

public class MyThread extends Thread{
    protected boolean exit = false;

    protected void kill(){
        exit = true;
 }
}

So when I create a thread, the method run() looks like :

public void run() {
    ...
    while(!exit) {
    ...
    }
}

My question is the following : I'm using my thread class to receive and send datagrams. But when the thread is waiting for a datagram, if I call the function MyThread.kill(), the thread will still wait a next packet before ending itself... How can I kill my thread without waiting for an another packet ? Thank you very much

2

There are 2 answers

0
David Schwartz On BEST ANSWER

After setting the exit flag, send the thread a datagram yourself to unblock it. By the way, exit should be volatile.

0
Paul Guyot On

The proper way to interrupt a call to DatagramSocket.receive() is to close the socket, and receive() will then throw a SocketException. So after setting the exit flag, you should close the UDP socket in your kill() method.