-1

Look at the code below, here's a question about it. Why I run this program, It won't stop when it comes the end? ( run it in eclipse, it need to stop manually.) Could anyone explain why?

public class C1 {
    public static void main(String[] args) {
        C1 c1 = new C1();
        c1.send();
    }
    private static final int POOL_SIZE = 5;
    private ExecutorService theadPool = Executors.newFixedThreadPool(POOL_SIZE);
    public void send() {
        this.theadPool.execute(new Runnable() {
            public void run() {
                System.out.println("haha");
            }
        });
    }
}
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
Marcus
  • 73
  • 1
  • 1
  • 7

1 Answers1

1

The thread pool contains threads that are not marked as "daemon" threads. A JVM exits when all non-daemon threads have terminated. Your "main" thread is terminating (when main returns) but the thread pool threads are still alive.

If you want the program to exit, either call System.exit(...) or call shutdown() on the executor.


Why are the threads in thread pool still alive?

Because the thread pool keeps them alive. One of the things that a thread pool does is to recycle threads ... because thread creation is expensive.

As the thread go to the last step (System.out.println("haha");), the thread won't stop?

Correct.

The actual threadpool thread's run() method will call your run() method. When your run() returns, the thread will wait for more tasks to be submitted via other calls to execute.

When all threads in thread pool come to the end, are they still alive?

Ermm ... the threads in a thread pool don't "come to the end". When a task is done, they wait for another task to be submitted.

The threadpool threads only finally terminate if you call shutdown or shutdownNow on the thread pool.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • Thanks a lot. But it's still a little not clear. Why are the threads in thread pool still alive? As the thread go to the last step (`System.out.println("haha");`), the thread won't stop? When all threads in thread pool come to the end, are they still alive? – Marcus Dec 16 '15 at 06:56
  • Thanks again. Stack overflow is a good place. I have posted this question in another forum before, but nobody can give me answer, utill I come here. – Marcus Dec 16 '15 at 07:32