为什么子线程不停止

问题描述 投票:0回答:1

我有一个以下简单的多线程程序。我预计

child thread
在主线程结束后不会启动或完成,但令我惊讶的是,我可以看到
##Child thread I=
的打印永远不会结束。

看起来我错过了一些非常基本的东西。有人可以指出为什么父线程完成后子线程仍在执行吗?

    public static void main(String[] args)
    {
        System.out.println("hello");
        new Thread(new Runnable()
        {
            int i = 0;
            public void run()
            {
                while (true)
                {
                    i++;
                    System.out.println("##Child thread i="+ i + "=th= "+ Thread.currentThread().getName());
                }

            }
        }).start();
        System.out.println("Main thread = "+ Thread.currentThread().getName());
    }
java multithreading
1个回答
0
投票

从头开始,Java 中的

Thread
不知道其父级
Thread
,因此它永远不会注意到该父级已死亡。

顺便说一句,父母

Thread
也不了解其孩子......

当然,您可以在父级中拥有子级

Thread
列表:

…
final List<Thread> children = new ArrayList<>();
final var thread = new Thread( task );
children.add( thread );
thread.start();
…

并且您可以在子级中引用父级:

public final class Action implement Runnable
{
  private final Thread m_Parent;
  private final Runnable m_Task;

  public Action( final Thread parent, final Runnable task )
  {
    m_Parent = parent;
    m_Task = task;
  }

  @Override
  public final void run()
  {
    while( m_Parent.isAlive )
    {
      m_Task.run();
    }
  }
}

但正如所说:开箱即用,没有这样的参考。

因此,任何非守护线程都会运行,直到它结束,或者直到它被中断(或者某些线程杀死 JVM – 或执行 JVM 的机器)。

相反,当当前 JVM 中的最后一个非守护线程死亡后,守护线程会自动死亡。

因此,对于您的示例,让您的线程成为守护进程(

Thread::setDaemon
,带有参数
true
),它将与主线程一起死亡。

© www.soinside.com 2019 - 2024. All rights reserved.