Java thread pool

Source: Internet
Author: User

We usually use multithreading in our code to improve the utilization of CPU and other resources. However, when threads in the CPU exceed the CPU schedule, our programs become slow and even deadlock causes the card death phenomenon.

There are also times when we need to create a huge number of threads. However, each thread has a relatively small run time. This consumes much more of the system resources when city threads and shutting down the threads than the time and resources spent processing the actual user requests. In addition to the overhead of creating and destroying threads, the active thread consumes system resources.

Creating too many threads in one JVM can cause the system to run out of memory or "over-switch" because of excessive memory consumption.

The emergence of thread pool can solve the above problems better, and the thread pool provides a solution to the problem of life cycle overhead and resource shortage.

By reusing threads on multiple tasks, the cost of thread creation is distributed across multiple tasks. The advantage is. Because the thread already exists when the request arrives. The delay caused by thread creation is also inadvertently eliminated. In this way, it is possible to service the request immediately. Make your application respond faster. Also, by adjusting the number of threads in the thread pool appropriately. That is, when the number of requests exceeds a certain threshold value. Forces other requests to wait for whatever new request is received until a thread is available to process it, thus preventing the resource from running out of resources.

Before using the thread pool. You must know how to create a thread pool in Java5. What you need to know is the API for the Java.util.concurrent.Executors class, which provides four common thread pools.

Mythread Class Code

public class MyThread extends Thread {       @Override public       void Run () {           System.out.println ( Thread.CurrentThread (). GetName () + "running:

"); } }


1.newCachedThreadPool

Newcachedthreadpool () creates new threads on demand, creates more, requires little, and the JVM itself slowly frees up redundant threads, 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.execute (t1);    Cachedthreadpool.execute (T2);    Cachedthreadpool.execute (T3);    Cachedthreadpool.execute (T4);    Cachedthreadpool.execute (T5);          Close the thread pool    cachedthreadpool.shutdown ();   }      }

Operating Effect:


2.newFixedThreadPool

Create a fixed thread pool. You can control the maximum number of concurrent threads, and the excess threads will wait in the queue.

When a new thread is added, it is assumed that the running thread has reached the upper limit and is blocked. Until a thread with the spare runs. He is a fixed-size thread pool.

Import Java.util.concurrent.ExecutorService;  Import java.util.concurrent.Executors;  public class Fixedthreadpool {public   static void Main (string[] args) {    Executorservice Fixedthreadpool = Executo Rs.newfixedthreadpool (3);    Thread T1 = new MyThread ();  Thread t2 = new MyThread ();  Thread t3 = new MyThread ();  Thread T4 = new MyThread ();  Thread T5 = new MyThread ();    Fixedthreadpool.execute (t1);    Fixedthreadpool.execute (T2);    Fixedthreadpool.execute (T3);    Fixedthreadpool.execute (T4);    Fixedthreadpool.execute (T5);      Close the thread pool    fixedthreadpool.shutdown ();   }  }  

at this point, the thread pool has a maximum of 3 threads, running the effect:


3.newScheduledThreadPool

Create a fixed-line pool that supports timed and recurring task runs. The sample code for the deferred run demo example is as follows:

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 an Runnable interface object that implements the. The thread object of course also implements the Runnable interface    thread t1 = new MyThread ();    Thread t2 = new MyThread ();    Thread t3 = new MyThread ();    Put the thread into the pool to run    scheduledthreadpool.execute (t1);    Methods of using the deferred run style    scheduledthreadpool.schedule (T2, timeunit.milliseconds);    Scheduledthreadpool.schedule (T3, ten, timeunit.milliseconds);    Close the thread pool    scheduledthreadpool.shutdown ();   }  }  
Run effect (delay process requires your own practice):

4.newSingleThreadExecutor

Creates a single threaded thread pool that runs tasks with only a single thread of work. Ensure that all tasks are run in the specified order (FIFO, LIFO, priority).

The demo 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.execute (t1);    Singlethreadexecutor.execute (T2);    Singlethreadexecutor.execute (T3);    Singlethreadexecutor.execute (T4);    Singlethreadexecutor.execute (T5);      Close the thread pool    singlethreadexecutor.shutdown ();   }  }  

Operating Effect:


The above four central thread pools are used in different scenarios and can be applied according to the actual situation in the project. The role of the thread pool is not only to control the number of threads created, but many others eliminate the frequent threading creation and destruction processes in multiple threads, reducing system destruction.


Java thread pool

Related Article

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.