What is a thread pool? Introduction to the use of Java four thread pool

Source: Internet
Author: User

There are many benefits of using the thread pool, such as saving system resources, saving time for creating and destroying threads, and so on, when we need to deal with more tasks, we can use the thread pool, and many users may not know how to use the Java thread pool? Here is a small series to share the Java four thread pool use method.

Thread Pool Description:

The thread pool is a form of multithreading that adds tasks to the queue during processing, and then automatically starts those tasks after the thread is created. Thread pool threads are all background threads. Each thread uses the default stack size, runs at the default priority, and is in a multithreaded apartment. If a thread is idle in managed code, such as waiting for an event, the thread pool inserts another worker thread to keep all the processors busy. If all thread pool threads are always busy, but the queue contains pending work, the thread pool will create another worker thread after a period of time but the number of threads will never exceed the maximum value. Threads that exceed the maximum value can be queued, but they will not start until other threads have finished.

Use of the Java four thread pool:

Java provides four thread pools through executors, namely:

Newcachedthreadpool creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable.

Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.

Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.

Newsinglethreadexecutor creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

(1) Newcachedthreadpool

Creates a cacheable thread pool that can flexibly reclaim idle threads if the thread pool length exceeds the processing needs, and creates a new thread if it is not recyclable. The sample code is as follows:

    1. 01package test;
    2. 02import Java.util.concurrent.ExecutorService;
    3. 03import java.util.concurrent.Executors;
    4. 04public class Threadpoolexecutortest {
    5. 05public static void Main (string[] args) {
    6. 06ExecutorService Cachedthreadpool = Executors.newcachedthreadpool ();
    7. 07for (int i = 0; i < i++) {
    8. 08final int index = i;
    9. 09try {
    10. 10thread.sleep (Index * 1000);
    11. One} catch (Interruptedexception e) {
    12. 12e.printstacktrace ();
    13. 13}
    14. 14cachedthreadpool.execute (New Runnable () {
    15. 15public void Run () {
    16. 16SYSTEM.OUT.PRINTLN (index);
    17. 17}
    18. 18});
    19. 19}
    20. 20}
    21. 21}
Copy Code

The thread pool is infinitely large, and when the first task is completed when the second task is performed, the threads that perform the first task are reused instead of each new thread.

(2) Newfixedthreadpool

Creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue. The sample code is as follows:

    1. 01package test;
    2. 02import Java.util.concurrent.ExecutorService;
    3. 03import java.util.concurrent.Executors;
    4. 04public class Threadpoolexecutortest {
    5. 05public static void Main (string[] args) {
    6. 06ExecutorService Fixedthreadpool = Executors.newfixedthreadpool (3);
    7. 07for (int i = 0; i < i++) {
    8. 08final int index = i;
    9. 09fixedthreadpool.execute (New Runnable () {
    10. 10public void Run () {
    11. 11try {
    12. 12SYSTEM.OUT.PRINTLN (index);
    13. 13thread.sleep (2000);
    14. \ catch (Interruptedexception e) {
    15. 15e.printstacktrace ();
    16. 16}
    17. 17}
    18. 18});
    19. 19}
    20. 20}
    21. 21}
Copy Code

Because the thread pool size is 3, each task outputs index after sleep for 2 seconds, so 3 digits are printed every two seconds.

The size of a fixed-length pool is best set based on system resources. such as Runtime.getruntime (). Availableprocessors ()

(3) Newscheduledthreadpool

Create a fixed-line pool that supports timed and recurring task execution. The deferred execution sample code is as follows:

    1. 01package test;
    2. 02import java.util.concurrent.Executors;
    3. 03import Java.util.concurrent.ScheduledExecutorService;
    4. 04import Java.util.concurrent.TimeUnit;
    5. 05public class Threadpoolexecutortest {
    6. 06public static void Main (string[] args) {
    7. 07ScheduledExecutorService Scheduledthreadpool = Executors.newscheduledthreadpool (5);
    8. 08scheduledthreadpool.schedule (New Runnable () {
    9. 09public void Run () {
    10. 10SYSTEM.OUT.PRINTLN ("Delay 3 seconds");
    11. 11}
    12. , 3, timeunit.seconds);
    13. 13}
    14. 14}
Copy Code

Represents a delay of 3 seconds for execution.

The sample code is executed periodically as follows:

    1. 01package test;
    2. 02import java.util.concurrent.Executors;
    3. 03import Java.util.concurrent.ScheduledExecutorService;
    4. 04import Java.util.concurrent.TimeUnit;
    5. 05public class Threadpoolexecutortest {
    6. 06public static void Main (string[] args) {
    7. 07ScheduledExecutorService Scheduledthreadpool = Executors.newscheduledthreadpool (5);
    8. 08scheduledthreadpool.scheduleatfixedrate (New Runnable () {
    9. 09public void Run () {
    10. 10SYSTEM.OUT.PRINTLN ("Delay 1 seconds, and excute every 3 seconds");
    11. 11}
    12. 1, 3, timeunit.seconds);
    13. 13}
    14. 14}
Copy Code

Represents a delay of 1 seconds after every 3 seconds.

(4) Newsinglethreadexecutor

Creates a single threaded thread pool that performs tasks with only a single worker thread, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority). The sample code is as follows:

    1. 01package test;
    2. 02import Java.util.concurrent.ExecutorService;
    3. 03import java.util.concurrent.Executors;
    4. 04public class Threadpoolexecutortest {
    5. 05public static void Main (string[] args) {
    6. 06ExecutorService singlethreadexecutor = Executors.newsinglethreadexecutor ();
    7. 07for (int i = 0; i < i++) {
    8. 08final int index = i;
    9. 09singlethreadexecutor.execute (New Runnable () {
    10. 10public void Run () {
    11. 11try {
    12. 12SYSTEM.OUT.PRINTLN (index);
    13. 13thread.sleep (2000);
    14. \ catch (Interruptedexception e) {
    15. 15e.printstacktrace ();
    16. 16}
    17. 17}
    18. 18});
    19. 19}
    20. 20}
    21. 21}
Copy Code

The results are output sequentially, which is equivalent to performing each task sequentially.

You can monitor the number of threads we create, run a non-terminating thread, and create a specified amount of threads, using the JDK's own monitoring tools to observe:

Tools Catalog: C:\Program files\java\jdk1.6.0_06\bin\jconsole.exe

Run the program to make a slight change:

    1. 01package test;
    2. 02import Java.util.concurrent.ExecutorService;
    3. 03import java.util.concurrent.Executors;
    4. 04public class Threadpoolexecutortest {
    5. 05public static void Main (string[] args) {
    6. 06ExecutorService singlethreadexecutor = Executors.newcachedthreadpool ();
    7. 07for (int i = 0; i <; i++) {
    8. 08final int index = i;
    9. 09singlethreadexecutor.execute (New Runnable () {
    10. 10public void Run () {
    11. 11try {
    12. 12while (True) {
    13. 13SYSTEM.OUT.PRINTLN (index);
    14. 14thread.sleep (10 * 1000);
    15. 15}
    16. The catch (Interruptedexception e) {
    17. 17e.printstacktrace ();
    18. 18}
    19. 19}
    20. 20});
    21. 21try {
    22. 22thread.sleep (500);
    23. (Interruptedexception e) {
    24. 24e.printstacktrace ();
    25. 25}
    26. 26}
    27. 27}
    28. 28}
Copy Code

The effect is as follows:

Select the program we run:

Monitor running status

About the Java four thread pool of the use of skills to share here, is the so-called 工欲善其事, its prerequisite, we have mastered the know-how, to deal with things can be less, hope can help everyone.

If there are deficiencies please understand: Write down your valuable message, I will promptly correct

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- ----------------

Great man Nice

e-mail: [Email protected]

qq:602091999

Cell-phone number:15800666248

http://www.cnblogs.com/lsw9/

Welcome harassment

If there are deficiencies please understand: Write down your valuable message, I will promptly correct

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------------------------------------------------------------- ----------------

great man Nice

e-mail: [Email protected]

qq:602091999

Cell-phone number:15800666248

http://www.cnblogs.com/lsw9/

Welcome harassment 

What is a thread pool? Introduction to the use of Java four thread pool

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.