I wrote this program for ThreadPoolExecutors
, it is simple enough.
package com.example.executors;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
public class ThreadPoolExecutorProg1 {
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor threadPoolExecutor = null;
// This is the task-1 which we want executor service to execute.
class MyRunnable1 implements Runnable {
@Override
public void run() {
System.out.println("Inside MyRunnable1#run().. working, I am being exercuted by thread --> " + Thread.currentThread());
}
}
// This is the task-2 which we want executor service to execute.
class MyRunnable2 implements Runnable {
@Override
public void run() {
System.out.println("Inside MyRunnable2#run().. working, I am being exercuted by thread --> " + Thread.currentThread());
}
}
// This is the task-3 which we want executor service to execute.
class MyRunnable3 implements Runnable {
@Override
public void run() {
System.out.println("Inside MyRunnable3#run().. working, I am being exercuted by thread --> " + Thread.currentThread());
}
}
// Creating an Executor service which has 10 threads.
threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
// Now, requesting Executor Service to "execute" each
// submitted Tasks.
threadPoolExecutor.execute(new MyRunnable1());
threadPoolExecutor.execute(new MyRunnable2());
threadPoolExecutor.execute(new MyRunnable3());
}
}
In main thread
, it is creating instance of ThreadPoolExecutor
. Each Runnable
tasks are executed by this ThreadPoolExecutor
.
The key point is, it is main thread
which created ThreadPoolExecutor
.
My doubt is: when Main thread
exits, that means there won't be any reference to ThreadPoolExecutor
using Main thread
. So how does ThreadPoolExecutor
continues to live even though Main thread
already exited?