Java中的子线程是否阻止父线程终止? [英] Does a child thread in Java prevent the parent threads to terminate?

查看:105
本文介绍了Java中的子线程是否阻止父线程终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在另一个线程中创建并启动一个线程时,它会是一个子线程吗?在子线程运行时是否阻止父线程终止?例如:

When I create and start a thread inside another thread, will it be a child thread? Does it prevent the termination of the parent thread while the child thread is running? For example:

new Thread(new Runnable() {
    @Override
    public void run() {
        //Do Sth
        new Thread(new Runnable() {
            @Override
            public void run() {
                //Do Sth
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //Do Sth
                    }
                }).start();
                //Do Sth
            }
        }).start();
        //Do Sth
    }
    //Do Sth            
}).start();


推荐答案

在你的代码中,有一个父子关系在对象之间。但是,线程之间没有父子关系的概念。一旦两个线程运行,它们基本上是对等的。

In your code, there is a parent-child relationship between objects. However, there is no notion of a parent-child relationship between threads. Once the two threads are running they're basically peers.

让我们说线程A启动线程B.除非它们之间有明确的同步,否则任何线程都可以随时终止不影响其他线程。

Let's say that thread A starts thread B. Unless there's explicit synchronisation between them, either thread can terminate whenever it pleases without affecting the other thread.

请注意,只要线程存在,任一线程都可以使进程保持活动状态。请参阅 Java中的守护程序线程是什么?

Note that either thread can keep the process alive for as long as the thread lives. See What is Daemon thread in Java?

这篇关于Java中的子线程是否阻止父线程终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆