Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Stop a thread automatically when program ends

Take a look at this code:

public class ThreadTest {

    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    //some code here
                }
            }
        }).start();

        System.out.println("End of main");
    }

}

Normally, when the end of main is reached, the program terminates. But in this example, the program will prints "End of main" and then keeps running because the thread is still running. Is there a way that the thread can stop automatically when the end is reached, without using something like while(isRunning)?

like image 398
Conner Dassen Avatar asked Mar 21 '18 16:03

Conner Dassen


2 Answers

The thread you are creating is independent and does not depend on the Main Thread termination. You can use Daemon thread for the same. Daemon threads will be terminated by the JVM when there are none of the other non- daemon threads running, it includes a main thread of execution as well.

public static void main(String[] args) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            while (true) {
                System.out.println("Daemon thread");
            }
        }
    });
    t.setDaemon(true);
    t.start();

    System.out.println("End of main");
}
like image 146
Amit Bera Avatar answered Nov 14 '22 13:11

Amit Bera


Make it a daemon thread.

public final void setDaemon(boolean on)

Marks this thread as either a daemon thread or a user thread. The Java Virtual Machine exits when the only threads running are all daemon threads. This method must be invoked before the thread is started.

Thread t = new Thread(new Runnable() {
    @Override
    public void run() {
        while(true) {
            //some code here
        }
    }
});

t.setDaemon(true);
t.start();

System.out.println("End of main");
like image 3
Michael Avatar answered Nov 14 '22 14:11

Michael