Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to stop thread if the program was closed

I'm getting some exception and I need to know when the program closes itself because I need to close the socket.

I have the default public static main method where I'm keep repeating an action and a Thread class.

private static Thread thread;
public static boolean isRunning = true;  

public static void main(String[] args){

   thread = new Thread(new ThreadListenServer());
   thread.start();

   Timer timer = new Timer();
   TimerTask task = new TimerTask() {
      @Override
      public void run(){
         // some action
      }
   }

   timer.scheduleAtFixedRate(task, 0, 10000);

   isRunning = false;
}

And the thread class which is running in background:

public class ThreadListenServer implements Runnable{

    private DatagramSocket socket;

    public ThreadListenServer() throws SocketException{
       socket = new DatagramSocket(6655);
    }

    @Override
    public void run() {

       while(MainProgram.isRunning){
            // some action
       }

       socket.close();
    }
}

I don't know why, but isRunning it's becoming false, but it shouldn't. How am I supposed to close the socket if the main program was closed? (It's causing because the Thread still running in the background even if the program was closed).

I was thinking about to create the socket in the main class then I pass the socket object as a parameter to the ThreadClass and if the program is closed, than I should close the socket as well.

like image 978
Zbarcea Christian Avatar asked Feb 16 '23 15:02

Zbarcea Christian


1 Answers

Use:

thread.setDaemon(true);

This will shut the thread. It tells the JVM it is a background thread , so it will shut down on exit.

like image 165
bluevoid Avatar answered Mar 06 '23 04:03

bluevoid