Thread Pool learning and thread pool

Source: Internet
Author: User

Thread Pool learning and thread pool

Creating a New thread and starting it will incur a high overhead, because the running thread requires more resources than calling the object method. In many cases, threads are used to execute a type of task, which has a large number of tasks and the time distribution is uneven. If a new thread is enabled for each new task, the overhead is too large. A performance optimization technology can be used, that is, the thread pool.

Place the threads of several execution tasks in the pool. When a task is to be executed, an idle thread is taken from the pool to process the task. After processing the task, the thread object is put into the pool. The thread pool is actually an object pool, but all objects in the pool are threads.

In this example, a thread pool is implemented to allocate tasks to the thread pool. The threads in the thread pool automatically obtain and execute the tasks.

Key Technologies: 1. thread group ThreadGroup can manage multiple threads, so let the thread pool inherit ThreadGroup.

2. When the thread pool is closed unconditionally, all threads in the pool are interrupted through the interrupt method of ThreadGroup.

3. When the Thread pool is closed with conditions, the ThreadGroup is used to obtain reference from all active threads in the pool, and the join method of Thread is called in sequence to wait for the execution of the active Thread to complete. When all threads are running, the thread pool can be closed.

4. Put the task in the Synchronized list. Because the Synchronized list does not support synchronization, you must use the Synchronized keyword in the method declaration for adding and obtaining tasks.

Instance

Package book. thread. pool;
/**
* Define the task interface class
*/
Public interface Task {
Public void perform () throws Exception;
}

Package book. thread. pool;

Public class MyTask implements Task {
Private int taskID = 0; // task ID
Public MyTask (int id ){
This. taskID = id;
}

@ Override
Public void perform () throws Exception {
System. out. println ("MyTask" + taskID + ": start ");
Thread. sleep (1000 );
System. out. println ("MyTask" + taskID + ": end ");
}
}

Package book. thread. pool;

Import java. util. Collections list;

Public class MyThreadPool extends ThreadGroup {
Private boolean isAlive; // indicates whether the thread pool is enabled.
Private queue list taskQueue; // task queue in the thread pool
Private int threadID; // The thread ID in the thread pool
Private static int threadPoolID; // thread pool ID
// Create a new thread pool. numThreads is the number of threads in the pool.
Public MyThreadPool (int numThreads ){
Super ("ThreadPool-" + (threadPoolID ++ ));
// Set the Daemon attribute of the thread pool to true, indicating that the thread pool will be destroyed automatically when all threads in the thread pool are destroyed.
Super. setDaemon (true );
This. isAlive = true;
This. taskQueue = new queue list (); // create a task queue
// Start numThreads worker threads
For (int I = 0; I <numThreads; I ++ ){
New PooledThread (). start ();
}
}
// Add a new task
Public synchronized void merge mtask (Task task ){
If (! This. isAlive ){
Throw new IllegalStateException (); // If the thread pool is disabled, an exception is thrown.
}
If (task! = Null ){
This. taskQueue. add (task); // put the task at the end of the task queue
Y (); // notify the worker thread to obtain the task
}
}
// Obtain the task
Protected synchronized Task getTask () throws InterruptedException {
// If the task list is empty and the thread pool is not closed, continue waiting for the task
While (this. taskQueue. size () = 0 ){
If (! This. isAlive ){
Return null;
}
Wait ();
}
// Obtain the first task in the task list
Return (Task) this. taskQueue. removeFirst ();
}
// Close the thread pool. All threads stop and no longer execute tasks.
Public synchronized void close (){
If (isAlive ){
This. isAlive = false;
This. taskQueue. clear (); // clear the task
This. interrupt (); // abort all threads in the thread pool
}
}
// Close the thread pool and wait until all tasks in the thread pool are completed, but new tasks cannot be received.
Public void join (){
// Notify other messages waiting for the thread "the thread pool is closed"
Synchronized (this ){
IsAlive = false;
Policyall ();
}
// Wait for all threads to complete. First, create a new thread group. The activeCount method gets the estimated number of active threads in the thread pool.
Thread [] threads = new Thread [this. activeCount ()];
// Copy the active thread in the thread pool to the newly created thread group threads.
Int count = this. enumerate (threads );
For (int I = 0; I <count; I ++ ){
Try {
Threads [I]. join (); // wait until the thread stops running
} Catch (InterruptedException e ){
E. printStackTrace ();
}
}
}
// Internal class, used to execute the job thread
Private class PooledThread extends Thread {
Public PooledThread (){
// The first parameter is the thread group object of the thread, that is, the current thread pool object.
// The second parameter is the thread name.
Super (MyThreadPool. this, "PooledThread-" + (threadID ++ ));
}
Public void run (){
// If the thread is not aborted
While (! IsInterrupted ()){
// Obtain the task
Task task = null;
Try {
Task = getTask ();
} Catch (InterruptedException e ){
E. printStackTrace ();
}
// As long as the task list in the thread pool is not empty, the getTask method will always get a task
// If getTask () returns null, it indicates that no task exists in the thread pool and the thread pool has been closed.
If (task = null ){
Return;
}
// Run the task to catch exceptions
Try {
Task. perform ();
} Catch (Exception e ){
UncaughtException (this, e );
}
}
}
}
}

Package book. thread. pool;

Public class PoolTest {
Public static void main (String [] args ){
Int numThreads = 3; // Number of threads in the thread pool
MyThreadPool threadPool = new MyThreadPool (numThreads); // generate a thread pool
Int numTasks = 10; // number of tasks
// Run the task
For (int I = 0; I <numTasks; I ++ ){
ThreadPool. Multiple mtask (new MyTask (I ));
}
// Close the thread pool and wait until all tasks are completed
ThreadPool. join ();
}
}

Output result:

MyTask 0: start
MyTask 1: start
MyTask 2: start
MyTask 0: end
MyTask 3: start
MyTask 1: end
MyTask 4: start
MyTask 2: end
MyTask 5: start
MyTask 3: end
MyTask 6: start
MyTask 4: end
MyTask 7: start
MyTask 5: end
MyTask 8: start
MyTask 6: end
MyTask 9: start
MyTask 7: end
MyTask 8: end
MyTask 9: end

Result Analysis: The MyThreadPool class is the main class of the thread pool, used to manage a group of working threads.

1. inherit from ThreadGroup. You can use the method provided by ThreadGroup to manage threads in the thread pool.

2. The mongomtask public synchronization method adds a task to the task queue of the thread pool. If the thread pool is disabled, that is, if the isAlive attribute is false, tasks cannot be added. After a task is added, the worker y method is called to notify the worker thread in the pool to obtain the task.

3. The getTask protected synchronization method obtains a task from the task queue in the thread pool. It is declared to be protected to restrict objects of other classes from illegally obtaining tasks. If no task exists in the task queue, the former thread enters the waiting state. If the thread pool is closed, null is returned directly.

4. The close method forces the thread pool to be closed. Use the interrupt method of ThreadGroup to interrupt all running threads in the thread pool, clear the task queue, and set the isAlive attribute to false, indicating that no new tasks are received.

5. The join method closes the thread pool with conditions. If the isAlive attribute is set to false, the Thread pool no longer receives new tasks. It obtains running threads through ThreadGroup and closes the Thread pool after they finish running the tasks through the Thread join method.

The PooledThread class is an internal class of MyThreadPool. It defines the working thread and is located in the MyThreadPool thread pool. After a task is retrieved from the task queue in the thread pool and obtained from the task, the perform method of the task is called to execute the task.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.