执行main方法后为什么Thread正在运行?

时间:2016-01-13 04:53:22

标签: java multithreading

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...");
    }
}

输出是:

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

4 个答案:

答案 0 :(得分:2)

当任何非daemon线程正在运行时,Java程序将继续运行。从下面的链接:"守护程序线程是一个线程,当程序完成但线程仍在运行时,它不会阻止JVM退出。守护程序线程的一个示例是垃圾回收。您可以使用setDaemon()方法更改Thread守护程序属性。" What is Daemon thread in Java?

默认情况下,所有创建的线程都是守护进程。您需要将其设置为非守护进程。

答案 1 :(得分:1)

你没有要求主线程在退出之前等待t1完成,因此两个线程之间根本没有同步(并且你没有任何关于它们中的每一个都将执行的保证他们的println)。

如果你想让主线程等待另一个,你应该使用join()函数,例如:

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

答案 2 :(得分:0)

或使用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...");
}

}

答案 3 :(得分:0)

如果你想知道程序何时完成,你需要一个关机钩子。从main返回不会杀死该程序。

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...");
        }
    });
}