public class ThreadPool extends Object
Runnable
tasks in a number of threads (over a number of CPU cores).
Usage:
ThreadPool pool = new ThreadPool(); pool.setThreadNamePrefix("foo"); // optional, for debugger output, default is class name pool.setThreadCount(5); // optional, default is number of CPU cores available pool.addTask(new Runnable() { ... }); // add one or more seed tasks; pool.execute(); // will start threads, execute the seed tasks, and execute any tasks they create
In the case that any task throws an exception, this exception is thrown by the execute()
method.
If all tasks run to completion, the execute()
method returns with no value.
The difference to an ExecutorService
is:
ExecutorService
the client adds a fixed number of tasks,
and they are then executed, without the executing tasks being able to add more tasks).
Such functionality is mandatory for web crawlers, which, during the processing of pages, discover links which
point to additional pages which require processing.ExecutorService
.
If the execute()
method is never called then no threads are ever started and the object can be garbage collected normally.
If the execute()
method is called then that method makes sure all threads it creates are destroyed.
Constructor and Description |
---|
ThreadPool() |
Modifier and Type | Method and Description |
---|---|
void |
addTask(Runnable r) |
void |
execute() |
void |
setThreadCount(int count) |
void |
setThreadNamePrefix(String prefix) |