Executors provides four thread pools

Source: Internet
Author: User

Java Concurrency Programming--executors

Thread pool idea is a kind of object pool idea, open a piece of memory space, inside contains many (not dead) threads, the pool thread execution schedule is handled by the pool manager. When a thread task is taken, one from the pool is executed and the object is returned to the pool. This avoids the performance overhead of repeatedly creating thread objects, saving the resources of the system.

Code: http://www.cnblogs.com/chenjingjing/articles/1683745.html

A fixed-size thread pool Newfixedthreadpool

Second, single task thread pool Newsinglethreadexecutor

for both of these connection pools, the size is fixed, and when the thread (or task) of the pool to be joined exceeds the maximum size of the pool, a queue waits for the pool to enter this thread. Once the threads in the pool are complete, a thread queued for execution is pooled.

Three, the variable size thread pool Newcachedthreadpool

Iv. delayed Connection pool Newscheduledthreadpool

V. custom thread pool threadpoolexecutor (one meal parameter)

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

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:

Java code
  1. Package test;
  2. Import Java.util.concurrent.ExecutorService;
  3. Import java.util.concurrent.Executors;
  4. Public class Threadpoolexecutortest {
  5. public static void Main (string[] args) {
  6. Executorservice Cachedthreadpool = Executors.newcachedthreadpool ();
  7. For (int i = 0; i < i++) {
  8. final int index = i;
  9. try {
  10. Thread.Sleep (Index * 1000);
  11. } catch (Interruptedexception e) {
  12. E.printstacktrace ();
  13. }
  14. Cachedthreadpool.execute (new Runnable () {
  15. public Void Run () {
  16. SYSTEM.OUT.PRINTLN (index);
  17. }
  18. });
  19. }
  20. }
  21. }

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:

Java code
  1. Package test;
  2. Import Java.util.concurrent.ExecutorService;
  3. Import java.util.concurrent.Executors;
  4. Public class Threadpoolexecutortest {
  5. public static void Main (string[] args) {
  6. Executorservice Fixedthreadpool = Executors.newfixedthreadpool (3);
  7. For (int i = 0; i < i++) {
  8. final int index = i;
  9. Fixedthreadpool.execute (new Runnable () {
  10. public Void Run () {
  11. try {
  12. SYSTEM.OUT.PRINTLN (index);
  13. Thread.Sleep (2000);
  14. } catch (Interruptedexception e) {
  15. E.printstacktrace ();
  16. }
  17. }
  18. });
  19. }
  20. }
  21. }


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:

Java code
  1. Package test;
  2. Import java.util.concurrent.Executors;
  3. Import Java.util.concurrent.ScheduledExecutorService;
  4. Import Java.util.concurrent.TimeUnit;
  5. Public class Threadpoolexecutortest {
  6. public static void Main (string[] args) {
  7. Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5);
  8. Scheduledthreadpool.schedule (new Runnable () {
  9. public Void Run () {
  10. SYSTEM.OUT.PRINTLN ("delay 3 seconds");
  11. }
  12. }, 3, timeunit.seconds);
  13. }
  14. }


Represents a delay of 3 seconds for execution.

The sample code is executed periodically as follows:

Java code
  1. Package test;
  2. Import java.util.concurrent.Executors;
  3. Import Java.util.concurrent.ScheduledExecutorService;
  4. Import Java.util.concurrent.TimeUnit;
  5. Public class Threadpoolexecutortest {
  6. public static void Main (string[] args) {
  7. Scheduledexecutorservice Scheduledthreadpool = Executors.newscheduledthreadpool (5);
  8. Scheduledthreadpool.scheduleatfixedrate (new Runnable () {
  9. public Void Run () {
  10. SYSTEM.OUT.PRINTLN ("Delay 1 seconds, and excute every 3 seconds");
  11. }
  12. }, 1, 3, timeunit.seconds);
  13. }
  14. }


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:

Java code
  1. Package test;
  2. Import Java.util.concurrent.ExecutorService;
  3. Import java.util.concurrent.Executors;
  4. Public class Threadpoolexecutortest {
  5. public static void Main (string[] args) {
  6. Executorservice singlethreadexecutor = Executors.newsinglethreadexecutor ();
  7. For (int i = 0; i < i++) {
  8. final int index = i;
  9. Singlethreadexecutor.execute (new Runnable () {
  10. public Void Run () {
  11. try {
  12. SYSTEM.OUT.PRINTLN (index);
  13. Thread.Sleep (2000);
  14. } catch (Interruptedexception e) {
  15. E.printstacktrace ();
  16. }
  17. }
  18. });
  19. }
  20. }
  21. }


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:

Java code
  1. Package test;
  2. Import Java.util.concurrent.ExecutorService;
  3. Import java.util.concurrent.Executors;
  4. Public class Threadpoolexecutortest {
  5. public static void Main (string[] args) {
  6. Executorservice singlethreadexecutor = Executors.newcachedthreadpool ();
  7. For (int i = 0; i < ; i++) {
  8. final int index = i;
  9. Singlethreadexecutor.execute (new Runnable () {
  10. public Void Run () {
  11. try {
  12. While (true) {
  13. SYSTEM.OUT.PRINTLN (index);
  14. Thread.Sleep ( 1000);
  15. }
  16. } catch (Interruptedexception e) {
  17. E.printstacktrace ();
  18. }
  19. }
  20. });
  21. try {
  22. Thread.Sleep (500);
  23. } catch (Interruptedexception e) {
  24. E.printstacktrace ();
  25. }
  26. }
  27. }
  28. }


The effect is as follows:

Select the program we run:

Monitor running status

Please go to Iteye website to see Java Xiao Qiang original, thank you!

http://cuisuqiang.iteye.com/!

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

Executors provides four 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.