简体   繁体   中英

Multithreading Parent and Child thread execution in Java

This is a beginner question regarding multithreading in 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 )

Then why am I not seeing the logs from the .log() being printed by Thread2 when the Main thread exits in the below code:

    @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?

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?

if the main thread finishes execution then another thread(Thread2) will still continue its execution

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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