本文介绍了Java-程序结束时自动停止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看看下面的代码:

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

}

通常,当到达main的结尾时,程序终止.但是在此示例中,程序将打印"main of End",然后继续运行,因为线程仍在运行.有没有一种方法可以使线程在结束时自动 停止,而无需使用while(isRunning)之类的东西?

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)?

推荐答案

您创建的线程是独立的,并且不依赖于主线程终止.您可以使用Daemon线程. 守护进程线程将在没有其他线程在运行时被JVM终止,它也包括一个执行主线程.

The thread you are creating is independent and does not depends on the Main Thread termination. You can use Daemon thread for same. Daemon threads will be terminated by the JVM when there are none of the other 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");
}

这篇关于Java-程序结束时自动停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 21:33