user1409534
user1409534

Reputation: 2304

Starting thread within a thread in Java

Say I have thread pool and I'm executing a task from that thread pool with thread with name thread-a Now within thread-a I'm starting a new thread lets call it thread-child (might be pooled thread and might not) does this means that thread-a is going back to the thread pool when thread-child get running? or thread-a is going to die?

Upvotes: 1

Views: 899

Answers (2)

dkb
dkb

Reputation: 4566

This is the actual answer : https://stackoverflow.com/a/56766009/2987755,
Just adding code in addition to that.

ExecutorService executorService = Executors.newCachedThreadPool();
Callable parentThread = () -> {
    System.out.println("In parentThread : " + Thread.currentThread().getName());
    Callable childThread = () -> {
        System.out.println("In childThread : " + 
        Thread.currentThread().getName());
        Thread.sleep(5000); // just to make sure, child thread outlive parent thread
        System.out.println("End of task for child thread");
        return 2; //ignore, no use here
    };
    executorService.submit(childThread);
    System.out.println("End of task for parent thread");
    return 1; //ignore, no use here
};
executorService.submit(parentThread);
Thread.sleep(8000); // wait until child thread completes its execution.
executorService.shutdown();

Output:

In parentThread : pool-1-thread-1
End of task for parent thread
In childThread : pool-1-thread-2
End of task for child thread

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

No. Java does not have an inheritance for threads. All threads are separate and self-sustained. I.e. your thread-a will be put back to execution pool. And thread-child will be executed until the end (no matter what has happened with thread-a) and will NOT be put into execution pool, because it was not created by it.

Upvotes: 6

Related Questions