Discuss / Java / 如果想父线程结束后,子线程就立刻结束应该怎么做呢?

如果想父线程结束后,子线程就立刻结束应该怎么做呢?

Topic source

无故之秋

#1 Created at ... [Delete] [Delete and Lock User]

子线程为守护线程,当父线程结束时,子线程(守护线程)并不会退出,而当main线程所有代码都执行完成后,结束当前进程。

public class TestMain {

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

        HelloThread t = new HelloThread();

        t.start();

        Thread.sleep(1000);

        t.terminate();

        Scanner scanner = new Scanner(System.in);

        String next = scanner.next();

        System.out.println(next);

    }

}

class HelloThread extends Thread {

    public void terminate() {

        running = false;

    }

    private volatile boolean running = true;

    @Override

    public void run() {

        Thread thread = new Thread(() -> {

            int n = 0;

            while (true) {

                System.out.println("Hello Daemon " + n++);

            }

        });

        thread.setDaemon(true);

        thread.start();

        int n = 0;

        while (running) {

            System.out.println("Hello Thread " + n++);

        }

    }

}

无故之秋

#2 Created at ... [Delete] [Delete and Lock User]

父子线程只是谁创建了谁的关系,并没有先后或从属之分,只要创建并运行后,这个所谓的子线程其实和父线程是相互独立的。

如果想要实现父线程结束时,子线程也结束的效果,可以在子线程中判断父线程是否存活,而将子线程设置为守护线程并没有这样的作用。

while (fatherThread.isAlive())

  • 1

Reply