Thread Pool
Thread pool concept: in fact, a receiving container multiple threads, which threads can be used repeatedly, often eliminating the need to create a thread object operation without repeatedly creates threads and consume too many resources.
Thread Pool: container -> set (ArrayList, HashSet, LinkedList <Thread>, HashMap)
- When the program first started, create multiple threads, save it to a collection
- When we want to use threads, can be taken out from the collection threads
T = list.remove the Thread (0 ); return element is removed, (thread can be used by one task)
the Thread linked.removeFist T = ();
- When we used up the thread, the thread needs to be returned to the thread pool
list.add(t);
linked.addLast(t);
After JDK1.5, JDK built-in thread pool, we can use the direct
benefits of rational use of the thread pool to bring:
- Reduce resource consumption
- Improve response time
- Thread improve manageability.
Code thread pool implementation: After providing the JDK1.5
java.util.concurrent.Executors; thread pool class factory for generating the thread pool
Executors class static method:
static ExecutorService newFixedThreadPool (int nThreads) to create a reusable fixed number of threads in the thread pool
parameter:
int nTherad: Create a number of threads in the thread pool included
return value:
ExecutorService interfaces, returns the class object implement ExecutorService interface, we can use the interface to receive ExecutorService (oriented programming interface)
java.util.concurrent.ExecutorService: thread pool Interface
- To obtain the thread from the thread pool, start method is called to open multiple threads, a thread of execution tasks
submit (Runnable task) Submits a Runnable task for execution
Close method / destroy the thread pool
void shutdown()
Thread pool using the steps:
- Static method using a thread pool inside the factory class Executors provided, newFixedThreadPool produce a specified number of threads the thread pool
- Create a class that implements the Runnable interface override the run method: to set the task thread
- ExecutorService submit method calls in, passing threaded tasks (implementation class), open thread, run method.
- ExecutorService method call in shotdown destruction thread pool (not recommended)
Es = Executors.newFixedThreadPool ExecutorService (2 )
es.submit (new new RunnableImpl ()); // create a new thread execution