简体   繁体   中英

Why Thread is running after execution of main method?

public class TestThread {

    public static void main(String[] args) {

        System.out.println("Main Prgm Started...");
        Thread t1=new Thread(new Runnable() {

            @Override
            public void run() {

                System.out.println("Thread is running..");
            }
        });

        t1.start();

        System.out.println("Main Prgm Exited...");
    }
}

Output is:

Main Prgm Started...
Main Prgm Exited...
Thread is running..

Java programs will continue to run while any non- daemon thread is running. From the link below: "A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread is still running. An example for a daemon thread is the garbage collection. You can use the setDaemon() method to change the Thread daemon properties." What is Daemon thread in Java?

By default all created threads are daemon. You need to set it as non daemon.

You are not asking your main thread to wait for t1 to finish before exiting so there is no synchronization at all between the two threads (and you don't have any guarantees about when each of them two will execute their println ).

If you want to make the main thread wait for the other then you should use join() function, eg:

t1.start();
t1.join();
System.out.println("Main Prgm Exited...");

or use CountDownLatch:

import java.util.concurrent.CountDownLatch;

public class TestThread {

public static void main(String[] args) {

    final CountDownLatch countDownLatch = new CountDownLatch(1);

    System.out.println("Main Prgm Started...");
    Thread t1=new Thread(new Runnable() {

        @Override
        public void run() {

            System.out.println("Thread is running..");
            countDownLatch.countDown();
        }
    });

    t1.start();

    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("Main Prgm Exited...");
}

}

If you want to know when a program is finished you need a shutdown hook. Returning from main won't kill the program.

public static void main(String[] args) {

    System.out.println("Main Prgm Started...");
    Thread t1=new Thread(new Runnable() {

        @Override
        public void run() {

            System.out.println("Thread is running..");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {}
            System.out.println("Thread is done..");
        }
    });
    t1.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            System.out.println("Main Prgm Exited...");
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM