Multithreaded Programming--4 thread pools

Source: Internet
Author: User

1. Classification
    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.
    2. Newfixedthreadpool creates a thread pool that controls the maximum number of concurrent threads, and the excess threads wait in the queue.
    3. Newscheduledthreadpool creates a fixed-line pool that supports timed and recurring task execution.
    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).
2, DOME2.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  Packagetest; 2 ImportJava.util.concurrent.ExecutorService; 3 Importjava.util.concurrent.Executors; 4  Public classThreadpoolexecutortest {5      Public Static voidMain (string[] args) {6Executorservice Cachedthreadpool =Executors.newcachedthreadpool (); 7          for(inti = 0; I < 10; i++) {  8             Final intindex =i; 9             Try {  TenThread.Sleep (Index * 1000);  One}Catch(interruptedexception e) { A E.printstacktrace ();  -             }   -Cachedthreadpool.execute (NewRunnable () { the                  Public voidrun () { - System.out.println (index);  -                 }   -             });  +         }   -     }   +}

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.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  Packagetest; 2 ImportJava.util.concurrent.ExecutorService; 3 Importjava.util.concurrent.Executors; 4  Public classThreadpoolexecutortest {5      Public Static voidMain (string[] args) {6Executorservice Fixedthreadpool = Executors.newfixedthreadpool (3); 7          for(inti = 0; I < 10; i++) {  8             Final intindex =i; 9Fixedthreadpool.execute (NewRunnable () {Ten                  Public voidrun () { One                     Try {   A System.out.println (index);  -Thread.Sleep (2000);  -}Catch(interruptedexception e) { the E.printstacktrace ();  -                     }   -                 }   -             });  +         }   -     }   +}

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 ()

2.3 Newscheduledthreadpool

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

1  Packagetest; 2 Importjava.util.concurrent.Executors; 3 ImportJava.util.concurrent.ScheduledExecutorService; 4 ImportJava.util.concurrent.TimeUnit; 5  Public classThreadpoolexecutortest {6      Public Static voidMain (string[] args) {7Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5); 8Scheduledthreadpool.schedule (NewRunnable () {9              Public voidrun () {TenSYSTEM.OUT.PRINTLN ("Delay 3 seconds");  One             }   A}, 3, Timeunit.seconds);  -     }   -}

Represents a delay of 3 seconds for execution.

The sample code is executed periodically as follows:

1  Packagetest; 2 Importjava.util.concurrent.Executors; 3 ImportJava.util.concurrent.ScheduledExecutorService; 4 ImportJava.util.concurrent.TimeUnit; 5  Public classThreadpoolexecutortest {6      Public Static voidMain (string[] args) {7Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5); 8Scheduledthreadpool.scheduleatfixedrate (NewRunnable () {9              Public voidrun () {TenSYSTEM.OUT.PRINTLN ("Delay 1 seconds, and excute every 3 seconds");  One             }   A}, 1, 3, Timeunit.seconds);  -     }   -}

Represents a delay of 1 seconds after every 3 seconds.

2.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  Packagetest; 2 ImportJava.util.concurrent.ExecutorService; 3 Importjava.util.concurrent.Executors; 4  Public classThreadpoolexecutortest {5      Public Static voidMain (string[] args) {6Executorservice Singlethreadexecutor =Executors.newsinglethreadexecutor (); 7          for(inti = 0; I < 10; i++) {  8             Final intindex =i; 9Singlethreadexecutor.execute (NewRunnable () {Ten                  Public voidrun () { One                     Try {   A System.out.println (index);  -Thread.Sleep (2000);  -}Catch(interruptedexception e) { the E.printstacktrace ();  -                     }   -                 }   -             });  +         }   -     }   +}

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

http://cuisuqiang.iteye.com/blog/2019372

Multithreaded Programming--4 thread pools

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.