简体   繁体   English

Java中的多线程父子线程执行

[英]Multithreading Parent and Child thread execution in Java

This is a beginner question regarding multithreading in Java.这是一个关于 Java 多线程的初学者问题。

As per my understanding when multiple (user)threads are created to run the program or application, then there is no concept of Parent and Child threads.根据我的理解,当创建多个(用户)线程来运行程序或应用程序时,则没有父线程和子线程的概念。 They are both independent user threads.它们都是独立的用户线程。

So, if the main thread finishes execution then another thread(Thread2) will still continue its execution because it will not be killed by the JVM until the Thread2's thread of execution is completed (https://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html , https://stackoverflow.com/a/9651919/6700081 )因此,如果主线程完成执行,则另一个线程(Thread2)仍将继续执行,因为在 Thread2 的执行线程完成之前它不会被 JVM 杀死(https://docs.oracle.com/javase/6 /docs/api/java/lang/Thread.html , https://stackoverflow.com/a/9651919/6700081 )

Then why am I not seeing the logs from the .log() being printed by Thread2 when the Main thread exits in the below code:那么为什么当主线程在以下代码中退出时,我没有看到.log()的日志被 Thread2 打印:

    @Test
    public void parentMainThreadAndChildThreadTest_WithSpringWebFlux() throws InterruptedException {
        Flux<Long> infiniteFlux = Flux.interval(Duration.ofMillis(100));
        infiniteFlux.subscribe((element) -> System.out.println("Value is:::" +element));
        Thread.sleep(3000); //Main thread sleeps for 3 seconds
    }

I see that if I increase the main thread's life by putting it to sleep then I can see the system out statements.我看到如果我通过将主线程置于睡眠状态来增加主线程的寿命,那么我可以看到系统输出语句。 But why aren't they displayed when the main thread is finished even though the Thread2 is still running asynchronously?但是为什么即使 Thread2 仍在异步运行,在主线程完成时它们也不显示?

The test method is executed by the Main thread's thread of execution so what happens to the Thread2 after main thread finishes in this case?测试方法是由主线程的执行线程执行的,那么在这种情况下主线程完成后Thread2会发生什么?

if the main thread finishes execution then another thread(Thread2) will still continue its execution如果主线程完成执行,则另一个线程(Thread2)仍将继续执行

this is true only for normal threads.这仅适用于普通线程。 Threads for thread pools usually are configured as daemon threads , which are forced to stop when all normal threads are finished.线程池的线程通常被配置为守护线程,当所有正常线程完成时,它们会被强制停止。

In your case,在你的情况下,

(element) -> System.out.println("Value is:::" +element)

is executed on a daemon thread taken from a reactor's thread pool.在从反应器的线程池中获取的守护线程上执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM