java線程--守護線程

public class Test {
    public static void main(String[] args) throws InterruptedException {

        DaemonThread daemon = new DaemonThread();
        daemon.setDaemon(true);
        // 先設置守護爲true,在開始線程
        daemon.start();
        Thread.sleep(2000);
        //主線程結束,守護線程跟着結束
    }

    static class DaemonThread extends Thread {

        @Override
        public void run() {

            while (true) {
                System.out.println("i am alive");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {

                    e.printStackTrace();
                }
            }

        }

    }
}
相關文章
相關標籤/搜索