Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit from a thread

I have the following block of code:

public void startListening() throws Exception {
    serverSocket = new DatagramSocket(port);
    new Thread() {

        @Override
        public void run() {
            System.out.print("Started Listening");
            byte[] receiveData = new byte[1024];
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            while (!stopFlag) {
                try {
                    serverSocket.receive(receivePacket);
                    String message = new String(receivePacket.getData());
                    System.out.println("RECEIVED: " + message);
                } catch (Exception ex) {
                    System.out.print("Execption :" + ex.getMessage());
                }
            }
        }
    }.start();
}


public void stopListening() {
    this.stopFlag = true;
}

Suppose I set stopFlag to true. serverSocket.receive(receivePacket); will wait until it receives a packet. What should I do if I want the thread to exit as soon as stopFlag is set to true.

like image 368
Akhil K Nambiar Avatar asked Apr 13 '12 07:04

Akhil K Nambiar


Video Answer


1 Answers

I had the same problem with a socket as well and interrupt() didn't work. My problem was solved by closing the socket. So in the setStop() method (as proposed above) you would have to call serverSocket.close() (you'd obviously have to make serverSocket a class member or something).

like image 176
mistalee Avatar answered Oct 09 '22 14:10

mistalee