Confused on Java ThreadPool

2019-02-27 20:25发布

问题:

It is my first time to use Java Thread Pool for my new project, after I came across this link http://www.javacodegeeks.com/2013/01/java-thread-pool-example-using-executors-and-threadpoolexecutor.html, I am more confused on this, here is the code from the page,

package com.journaldev.threadpool;

public class WorkerThread implements Runnable {

    private String command;

    public WorkerThread(String s){
        this.command=s;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+' Start. Command = '+command);
        processCommand();
        System.out.println(Thread.currentThread().getName()+' End.');
    }

    private void processCommand() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString(){
        return this.command;
    }
}


package com.journaldev.threadpool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleThreadPool {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 10; i++) {
            Runnable worker = new WorkerThread('' + i);
            executor.execute(worker);
          }
        executor.shutdown();
        while (!executor.isTerminated()) {
        }
        System.out.println('Finished all threads');
    }

}

in the code, a fixed size pool is created and 10 worker threads are created, am I right?

The thread pool is supposed to decrease the burden of a system, on the contrary, in the above code, I think it increases the burden by creating the pool in addition to the worker threads. why bother to use the thread pool?

Can anyone explain? Thanks

I also read this post on StackOverflow http://stackoverflow.com/questions/19765904/how-threadpool-re-use-threads-and-how-it-works it did not help me either.

回答1:

This is confusing because the Runnables are named WorkerThread, but they don't extend java.lang.Thread, they're just objects that implement Runnable. Implementing Runnable lets you specify a task that needs to be executed without having to instantiate an actual Thread object. The only threads created in your example are the main thread and the ones created by the Executor.

Note that, even if you change this code to make WorkerThread extend Thread, as long as the code doesn't call start on them it wouldn't result in more threads actually running. Constructing a thread object involves some things like checking with the Security Manager and initializing threadlocals, but it doesn't actually do anything at the OS-level to allocate a thread. As far as the Executor is concerned they're just Runnables, it would execute them using the threadpool's threads.



回答2:

Bad example! The class called WorkerThread is not a thread, it is a "task".

The threads are hidden inside the ExecutorService. The example creates an ExecutorService with five "worker" threads, it creates ten tasks, it asks the executor service to "perform" them, and then finally, it waits for all of the tasks to be completed. It's totally up to the ExecutorService to decide how and when and in which worker thread to perform each task.

Another lesser problem with the example is how the main thread waits after asking the executor service to shut down. It spins, using CPU resources that maybe could have been used by one or more of the workers (depends on how many CPUs the host has available to run the various threads.) The wait loop should call Thread.yield() which gives up the main thread's time slice to any other runnable thread each time it is called.