how to stop main thread while another thread still running

java, multithreading

Solution

Regular Threads can prevent the VM from terminating normally (i.e. by reaching the end of the main method - you are not using System#exit() in your example, which will terminate the VM as per documentation).

For a thread to not prevent a regular VM termination, it must be declared a daemon thread via Thread#setDaemon(boolean) before starting the thread.

In your example - the main thread dies when it reaches the end of it code (after t1.start();), and the VM - including t1- dies when t1 reaches the end of its code (after the while(true) aka never or when abnormally terminating.)

Compare this question, this answer to another similar question and the documentation.

Problem

I started t1 thread in my main method and want to stop main thread but my t1 thread still running. It is possible? how? ``` public static void main(String[] args) { Thread t1=new Thread() { public void run() { while(true) { try { Thread.sleep(2000); System.out.println("thread 1"); } catch(Exception e) {} } } }; t1.start(); } ```

Original source

Related problems