Java notes-optimizing multithreaded programming with a thread pool

Source: Internet
Author: User

Optimizing multithreaded programming with a thread pool

Understanding Thread Pools

In Java, all objects need to be created with the new operator,
If you create a large number of short-life-cycle objects, the performance of the entire program will be very low.
This is the time to use the technology of the pool, such as database connection pool, thread pool and so on.

After java1.5, Java comes with a thread pool and adds a concurrent package under the Util package.
The main purpose of this package is to introduce how Java threads and thread pools are used.

The executors class under package java.util.concurrent defines executor, Executorservice, Scheduledexecutorservice,
Threadfactoryscheduledexecutorservice, Threadfactory and callable plants and practical methods.

This class supports the following various methods :
A. Create and return a method that sets the executorservice of a common configuration string.
B. Create and return a method that sets the scheduledexecutorservice of a common configuration string.
C. Create and return a "wrapped" Executorservice method that disables reconfiguration by making the implementation-specific method inaccessible.
D. Create and return a Threadfactory method that sets the newly created thread to a known state.
E. Create and return a method for callable in a non-enclosed form, which can be used in an execution method that requires callable.
--If you want to reprint this article please indicate the reprint address "http://www.cnblogs.com/XHJT/p/3897773.html" Thank you--
First, let's compare the differences between creating multiple threads with a thread pool and creating multiple threads in a stand-alone way.
Here we will illustrate the necessity and importance of thread pooling by comparing two methods to occupy memory and spend time .

code example:

Package Com.xhj.thread;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;/** *  Compare the pros and cons of creating threads independently and thread pools-time and memory consumption * * @author Xiehejun * */public class Comparethreadpool implements Runnable {private    int id = 0;    @Override public void Run () {id++; } public static void Main (string[] args) {/** * creates 1000 threads independently */{//Gets the current program runtime            Object Runtime Run = Runtime.getruntime ();            Call the garbage collection mechanism to reduce memory error run.gc ();            Gets the idle memory of the current JVM long freememory = Run.freememory ();            System Current Time Long Timepro = System.currenttimemillis (); Independently creates and executes 1000 threads for (int i = 0; i < i++) {new Thread (new Comparethreadpool ()). Start (            );            SYSTEM.OUT.PRINTLN ("The amount of memory required to create and execute 1000 threads independently:" + (Freememory-run.freememory ()));            System.out.println ("The time required to create and run 1000 threads independently is:"        + (System.currenttimemillis ()-Timepro)); /** * Create 1000 threads using thread pool */{//Get current Program Runtime object runtime Run = Runtime.getru            Ntime ();            Call the garbage collection mechanism to reduce memory error run.gc ();            Gets the idle memory of the current JVM long freememory = Run.freememory ();            System Current Time Long Timepro = System.currenttimemillis ();            Executorservice service = Executors.newfixedthreadpool (2);            Independently creates and executes 1000 threads for (int i = 0; i < i++) {Service.submit (New Comparethreadpool ()); } System.out.println ("The amount of memory required to create 1000 threads using the thread pool:" + (Freememory-run.freememory ()            ));            Thread pooling is done, close thread pool Service.shutdown ();        System.out.println ("The time required to create and run 1000 threads using a thread pool is:" + (System.currenttimemillis ()-Timepro)); }    }}

The result is:

conclusion-Why use a thread pool:
From the above example, we know that using the thread pool can greatly improve the performance of the system and improve the execution efficiency of the program tasks.
Saves the memory space of the system. In the thread pool, each worker thread can be reused to perform multiple tasks,
Reduces the number of times the thread is created and destroyed. The ability to adjust the number of threads according to the system's endurance, so that the system can achieve the best performance.


Thread pool principle:
There are multiple threads in a thread pool that are in a running state, and when you add an runnable or callable interface object to the thread pool,
There is a thread that executes the run () method or the call () method. If the method finishes executing, the thread does not terminate,
Instead, it continues to be in a running state in the pool to run the new task.

Understanding Thread Pools (several common static methods for creating thread pools in Java)

In Java, the top-level interface of the thread pool is the Executors tool class under the Util.concurrent package , where many methods of manipulating the thread pool are defined.
Among the most commonly used thread pools are:
1. Create a single thread pool:
newsinglethreadexecutor (), create a thread pool with only one threads, which performs all tasks in the order in which they are submitted.
In the event of an abnormal interruption, the thread pool will re-establish a single thread instead of completing the subsequent work.

code example:

    /**     * Create a thread pool with a single thread *      * @return *     /public    Executorservice Singlethreadpool () {        Executorservice Singlepool = Executors.newsinglethreadexecutor ();        return singlepool;    }

2. Create a cacheable thread pool:
Newcachedthreadpool (),
create an unlimited size, and only the thread pool, he will be based on the amount of task to open up and reduce memory space,
But the size of thread pool threads depends on the performance of the system or the capacity of the JVM

code example:

   /**     * Create a cacheable thread pool      *      * @return *     /public    Executorservice Cachedthreadpool () {        Executorservice Cachedpool = Executors.newcachedthreadpool ();        return cachedpool;    }

3. Create a thread pool with a fixed size:
Newfixedthreadpool (),
creates a fixed-size thread pool, the task commits the thread until the thread size reaches the maximum allowable value,
The thread pool complements a new thread if it ends.

code example:

   /**     * Create a thread pool of fixed size *      * @return *    /public Executorservice Fixedthreadpool () {        Executorservice Fixedpool = Executors.newfixedthreadpool (2);        return fixedpool;    }


4. Create a thread pool that can be timed and executed periodically
Newscheduledthreadpool (),
create a thread pool that can be timed, periodically executed, with no size limit for this thread pool,
Implement periodic task scheduling.

code example:

Scheduledthreadpoolexecutor Scheduledpool = new Scheduledthreadpoolexecutor (1);


To make it easier for you to understand and compare the differences, the following will integrate these common thread pools into one program,

code example:

Package Com.xhj.thread;import Java.util.scanner;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.scheduledthreadpoolexecutor;import  java.util.concurrent.timeunit;/** * Understanding and application of several common thread pools * * @author Xiehejun * */public class Createthreadpools extends thread                {@Override public void run () {System.out.println ("System time:" + system.currenttimemillis () + "Thread:" + Thread.CurrentThread (). GetName () + "Executing!!    "); }/** * Create a single thread pool * * @return */public Executorservice Singlethreadpool () {Executorservi        Ce singlepool = executors.newsinglethreadexecutor ();    return singlepool; /** * Create a thread pool of fixed size * * @return */public Executorservice Fixedthreadpool () {Executorservi        Ce fixedpool = executors.newfixedthreadpool (3);    return fixedpool;   }/** * Create a cacheable thread pool * * @return */public Executorservice Cachedthreadpool () {     Executorservice Cachedpool = Executors.newcachedthreadpool ();    return cachedpool; /** * Put the created thread into the threads pool and execute * * @param pool */public void service (Executorservice pool) {//Gen        Build Thread thread1 = new Createthreadpools ();        Thread thread2 = new Createthreadpools ();        Thread thread3 = new Createthreadpools ();        Thread thread4 = new Createthreadpools ();        Thread thread5 = new Createthreadpools ();        Threads into the thread pool and executes Pool.execute (THREAD1);        Pool.execute (THREAD2);        Pool.execute (THREAD3);        Pool.execute (THREAD4);        Pool.execute (THREAD5);    Close the thread pool Pool.shutdown (); /** * Create an unlimited thread pool, available with timed and recurring services */public void Scheduledthreadpool () {Scheduledthreadpoolexecutor        Scheduledpool = new Scheduledthreadpoolexecutor (1); Scheduledpool.scheduleatfixedrate (New Runnable () {@Override public void run () {Syst Em.out.println ("======= "+ system.currenttimemillis () +" ========= ");        }}, +, timeunit.milliseconds); Scheduledpool.scheduleatfixedrate (New Runnable () {@Override public void run () {Syst            Em.out.println (System.nanotime ());    }}, +, timeunit.milliseconds);        } public static void Main (string[] args) {Createthreadpools creatthreadpool = new Createthreadpools ();        Scanner sc = new Scanner (system.in);            while (true) {System.out.println ("Choose to create a thread pool: 1. Single thread thread pool; 2. Cache thread pool; 3. Fixed size thread pool; 4 periodic thread pool execution)";            int i = Sc.nextint ();                switch (i) {case 1:system.out.println ("-----calls a single thread pool-----");                Call a single thread pool Creatthreadpool.service (Creatthreadpool.singlethreadpool ());            Break                Case 2:SYSTEM.OUT.PRINTLN ("-----calls the thread pool of the cacheable thread-----");      To invoke a thread pool that caches threads          Creatthreadpool.service (Creatthreadpool.cachedthreadpool ());            Break                Case 3:SYSTEM.OUT.PRINTLN ("-----calls the thread pool for fixed-size threads-----");                Call thread pool Creatthreadpool.service (Creatthreadpool.fixedthreadpool ()) For fixed-size threads;            Break                Case 4:SYSTEM.OUT.PRINTLN ("-----Call the size of the thread pool that is unlimited, timed and periodically executed-----");                Call thread pool Creatthreadpool.scheduledthreadpool () for fixed-size threads;            Break }        }    }}

Note: When the thread pool task finishes, be sure to remember to close the thread pool and execute the shutdown () method.
     

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.