Java Thread Pool

Source: Internet
Author: User

Java Thread Pool

We usually use multithreading in writing programs to improve the utilization of CPU and other resources. However, when the threads in the CPU exceed the CPU scheduling range, our programs will become slow and even cause deadlocks and program freezing. There are also many times that we need to create a large number of threads, but the execution time of each thread is relatively small, in this way, the system resources consumed when the new thread is started and the thread is closed are more time and resources than the actual user requests are processed. In addition to the overhead of creating and destroying threads, active threads also consume system resources. Creating too many threads in a JVM may cause the system to use up memory or "over-switching" due to excessive memory consumption ".

The emergence of the thread pool can better solve the above problems. The thread pool provides a solution for thread lifecycle overhead and resource insufficiency issues. By reusing threads for multiple tasks, the overhead created by threads is apportioned to multiple tasks. The advantage is that the thread already exists when the request arrives, so the delay caused by thread creation is accidentally eliminated. In this way, the application can immediately respond to the request. In addition, adjust the number of threads in the thread pool appropriately, that is, when the number of requests exceeds a certain threshold, force any other new requests to wait, wait until a thread is obtained for processing to prevent resource insufficiency.

Before using the thread pool, you must know how to create a thread pool. in java 5, you must understand java. util. concurrent. executors class API, which provides four common thread pools.

MyThread code

Public class MyThread extends Thread {@ Override public void run () {System. out. println (Thread. currentThread (). getName () + "is being executed... ");}}
1. newCachedThreadPool

NewCachedThreadPool () is used to create new threads based on requirements. When many threads are required, more threads are created. When few threads are required, the JVM will slowly release redundant threads, it is a variable-size thread pool.

Import java. util. concurrent. executor; import java. util. concurrent. executorService; import java. util. concurrent. executors; public class CachedThreadPool {public static void main (String [] args) {ExecutorService cachedThreadPool = Executors. newCachedThreadPool (); Thread t1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread t4 = new MyThread (); thread t5 = new MyThread (); cachedThreadPool.exe cute (t1); cachedThreadPool.exe cute (t2); cachedThreadPool.exe cute (t3); cachedThreadPool.exe cute (t4); cachedThreadPool.exe cute (t5 ); // close the thread pool cachedThreadPool. shutdown ();}}
Running effect:

2. newFixedThreadPool

Create a fixed-length thread pool to control the maximum number of concurrent threads. threads that exceed the limit will wait in the queue. After a new thread is added, if the running thread reaches the upper limit, it will be blocked until there is idle thread to run. It is a thread pool with a fixed length.

 

Import java. util. concurrent. executorService; import java. util. concurrent. executors; public class FixedThreadPool {public static void main (String [] args) {ExecutorService fixedThreadPool = Executors. newFixedThreadPool (3); Thread t1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread t4 = new MyThread (); thread t5 = new MyThread (); fixedThreadPool.exe cute (t1); fixedThreadPool.exe cute (t2); fixedThreadPool.exe cute (t3); fixedThreadPool.exe cute (t4); fixedThreadPool.exe cute (t5 ); // close the thread pool fixedThreadPool. shutdown ();}}
The maximum thread in the thread pool is 3. Running effect:

3. newScheduledThreadPool

Creates a fixed-length thread pool that supports scheduled and periodic task execution. Example code of delayed execution:

 

Import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit; public class ScheduledThredPool {public static void main (String [] args) {ScheduledExecutorService scheduledThreadPool = Executors. newScheduledThreadPool (2); // creates and implements the Runnable interface object. Of course, the Thread object also implements the Runnable interface Thread t1 = new MyThread (); Thread t2 = new MyThread (); thread t3 = new MyThread (); // put the Thread into the pool to execute scheduledThreadPool.exe cute (t1); // use the delayed execution style method scheduledThreadPool. schedule (t2, 1000, TimeUnit. MILLISECONDS); scheduledThreadPool. schedule (t3, 10, TimeUnit. MILLISECONDS); // closes the thread pool scheduledThreadPool. shutdown ();}}
Running Effect (you need to practice the Delay Process ):

4. newSingleThreadExecutor

Create a single-threaded thread pool. It only uses a unique worker thread to execute tasks and ensures that all tasks are executed in the specified order (FIFO, LIFO, priority. The sample code is as follows:

 

Import java. util. concurrent. executorService; import java. util. concurrent. executors; public class SingleThreadExecutor {public static void main (String [] args) {ExecutorService singleThreadExecutor = Executors. newSingleThreadExecutor (); Thread t1 = new MyThread (); Thread t2 = new MyThread (); Thread t3 = new MyThread (); Thread t4 = new MyThread (); thread t5 = new MyThread (); singleThreadExecutor.exe cute (t1); singleThreadExecutor.exe cute (t2); merge cute (t3); singleThreadExecutor.exe cute (t4); singleThreadExecutor.exe cute (t5 ); // close the singleThreadExecutor of the thread pool. shutdown ();}}

Running effect:

The preceding four thread pools are used in different scenarios. You can select an application in the project based on the actual situation. The thread pool is not only used to control the number of threads created, in addition, frequent thread creation and destruction processes are eliminated in multiple threads, reducing system destruction.

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.