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.