Java thread (5): Thread Pool

Source: Internet
Author: User

Since JDK5, Java has launched a concurrent package, java. util. concurrent, in Java Development, we have come into contact with many pool technologies, such as the object pool of the String class, the sharing pool of Integer, the connection pool to connect to the database, and the object pool of Struts1.3, the ultimate goal of the pool is to save resources and do more things with less overhead, thus improving performance.
Our web projects are deployed on the server, and each request on the browser side is a thread. Therefore, if the server needs to process multiple requests concurrently, the thread pool technology is required, the following describes how to create a thread pool in a Java concurrent package.
1. Create a thread pool that can reuse a set of fixed threads and run these threads in a shared unbounded queue mode.
[Java]
ExecutorService threadPool = Executors. newFixedThreadPool (3); // create a thread pool that can accommodate three threads
2. Create a thread pool where new threads can be created as needed, but they will be reused when previously constructed threads are available.
[Java]
ExecutorService threadPool = Executors. newCachedThreadPool (); // The thread pool size is dynamically allocated based on the number of executed tasks.
3. Create an Executor that uses a single worker thread to run this thread in the unbounded queue mode.
[Java]
ExecutorService threadPool = Executors. newSingleThreadExecutor (); <pre name = "code" class = "java"> // creates a thread pool for a single thread. If the current thread is suddenly interrupted during task execution, A new thread will be created to replace it to continue executing the task.
4. Create a thread pool that can be scheduled to run commands or regularly run after a given delay.
[Java]
ScheduledExecutorService threadPool = Executors. newScheduledThreadPool (3); // effect similar to Timer
Each thread pool has different use cases. Let's take a look at the differences between these four thread pools.
1. FixedThreadPool
[Java]
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
Public class ThreadPoolTest {
Public static void main (String [] args ){
ExecutorService threadPool = Executors. newFixedThreadPool (3 );
For (int I = 1; I <5; I ++ ){
Final int taskID = I;
ThreadPool.exe cute (new Runnable (){
Public void run (){
For (int I = 1; I <5; I ++ ){
Try {
Thread. sleep (20); // to test the effect, it takes some time to execute each task.
} Catch (InterruptedException e ){
E. printStackTrace ();
}
System. out. println ("th" + taskID + "" + I + "");
}
}
});
}
ThreadPool. shutdown (); // After the task is executed, close the thread pool.
}
}
Output result:
[Java]
1st executions of 1st tasks
2nd executions of 1st tasks
3rd executions of 1st tasks
2nd executions of 2nd tasks
3rd executions of 2nd tasks
1st executions of 2nd tasks
3rd executions of 3rd tasks
1st executions of 3rd tasks
2nd executions of 3rd tasks
3rd executions of 4th tasks
2nd executions of 4th tasks
1st executions of 4th tasks
4th executions of 1st tasks
4th executions of 2nd tasks
4th executions of 3rd tasks
4th executions of 4th tasks
In the code above, a fixed thread pool with a capacity of 3 is created, and four tasks are executed cyclically. The output result shows that the first three tasks are completed first, then the idle thread executes 4th tasks. In the FixedThreadPool, there is a fixed-size pool. If the number of tasks to be executed exceeds the pool size, more tasks are waiting, until there are Idle threads to execute the task, and when the executed task is smaller than the pool size, Idle threads will not be destroyed.
2. CachedThreadPool
The previous Code remains unchanged elsewhere. Replace the newFixedThreadPool method with the newCachedThreadPool method.
Output result:
[Java]
3rd executions of 1st tasks
4th executions of 1st tasks
1st executions of 1st tasks
2nd executions of 1st tasks
4th executions of 2nd tasks
3rd executions of 2nd tasks
2nd executions of 2nd tasks
1st executions of 2nd tasks
2nd executions of 3rd tasks
3rd executions of 3rd tasks
1st executions of 3rd tasks
4th executions of 3rd tasks
2nd executions of 4th tasks
4th executions of 4th tasks
3rd executions of 4th tasks
1st executions of 4th tasks
It can be seen that four tasks are executed alternately. CachedThreadPool creates a cache zone and caches the initialization thread. If the thread is available, it uses the previously created thread, if no thread is available, a new thread is created, terminated, and the unused thread is removed from the cache for 60 seconds.
3. Change the newFixedThreadPool method to the newSingleThreadExecutor method. Output result:
[Java]
1st executions of 1st tasks
1st executions of 2nd tasks
1st executions of 3rd tasks
1st executions of 4th tasks
2nd executions of 1st tasks
2nd executions of 2nd tasks
2nd executions of 3rd tasks
2nd executions of 4th tasks
3rd executions of 1st tasks
3rd executions of 2nd tasks
3rd executions of 3rd tasks
3rd executions of 4th tasks
4th executions of 1st tasks
4th executions of 2nd tasks
4th executions of 3rd tasks
4th executions of 4th tasks
The four tasks are executed sequentially. SingleThreadExecutor obtains a single thread, which ensures that your task is executed completely. If the current thread terminates unexpectedly, A new thread will be created to continue executing the task, which is different from creating a thread directly. It is also different from newFixedThreadPool (1.
4. ScheduledThreadPool
[Java]
Import java. util. concurrent. ScheduledExecutorService;
Import java. util. concurrent. TimeUnit;
Public class ThreadPoolTest {
Public static void main (String [] args ){
ScheduledExecutorService schedulePool = Executors. newScheduledThreadPool (1 );
// Execute the task in 5 seconds
SchedulePool. schedule (new Runnable (){
Public void run (){
System. out. println ("explosion ");
}
}, 5, TimeUnit. SECONDS );
// Execute the task after 5 seconds, and then execute the task every 2 seconds
SchedulePool. scheduleAtFixedRate (new Runnable (){
@ Override
Public void run (){
System. out. println ("explosion ");
}
}, 5, 2, TimeUnit. SECONDS );
}
}
ScheduledThreadPool is a fixed-size thread pool. Similar to FixedThreadPool, the task is scheduled.

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.