Discuss / Java / 练习:使用守护线程

练习:使用守护线程

Topic source

韦雪松

#1 Created at ... [Delete] [Delete and Lock User]
public class Main {
    public static void main(String[] args) {
        System.out.println("main: start.");

        Thread t = new Thread(() -> {
            for (; ; ) {
                System.out.println("Thread-1: running...");
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.setDaemon(true);//设置为守护线程【表示守护主线程,随主线程结束而结束】
        t.start();

        System.out.println("main: wait 3 sec...");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("main: end.");
    }
}

  • 1

Reply