Java multi-thread thread pool

Source: Internet
Author: User
Tags terminates

Since JDK5, Java has introduced a contract,Java.util.concurrent, in Java development, we have access to a lot of pool technology, the object pool of string class, the shared pool of integers, connection pool connected to the database, Struts1.3 object pool And so on, the ultimate goal of the pool is to conserve resources and do more with less overhead, thus improving performance.

Our Web projects are deployed on the server, each request on the browser side is a thread, then the server needs to handle multiple requests concurrently, it requires thread pooling technology, below to see how Java Concurrent package to create a thread pool.

1. Create a thread pool that can reuse fixed thread collections to run these threads in a shared, unbounded queue.

1  Executorservice ThreadPool = Executors.newfixedthreadpool (3); // Create a thread pool  that can hold 3 threads

2. Create a thread pool that can create new threads as needed , but reuse them when previously constructed threads are available.

1 executorservice threadPool = Executors.newcachedthreadpool (); // the size of the thread pool is dynamically allocated  based on the number of tasks performed

3. Create a Executor that uses a single worker threadto run the thread in a unbounded queue.

1 executorservice threadPool = Executors.newsinglethreadexecutor (); // creates a thread pool of a single threads, and if the current thread breaks abruptly when the task is executed, a new thread is created to replace  it to continue the task

4. Create a thread pool that can schedule a command to run after a given delay or to execute periodically.

Scheduledexecutorservice ThreadPool = Executors.newscheduledthreadpool (3); // effect similar to timer timer  

Each thread pool has a different usage scenario, so let's look at the differences between the four thread pools used.

1. Fixedthreadpool

1 ImportJava.util.concurrent.ExecutorService; 2 Importjava.util.concurrent.Executors; 3  Public classThreadpooltest {4      Public Static voidMain (string[] args) {5Executorservice ThreadPool = Executors.newfixedthreadpool (3); 6          for(inti = 1; I < 5; i++) {  7             Final intTaskID =i; 8Threadpool.execute (NewRunnable () {9                  Public voidrun () {Ten                      for(inti = 1; I < 5; i++) {   One                         Try {   AThread.Sleep (20);//To test the results, it takes time for each task to execute. -}Catch(interruptedexception e) { - E.printstacktrace ();  the                         }   -System.out.println ("+ TaskID +" sub-task "+ i +" execution "));  -                     }   -                 }   +             });  -         }   +Threadpool.shutdown ();//the task is completed and the thread pool is closed A     }   at}

Output Result:

  1. 1 Executions of the first 1 missions
  2. 1 Executions of the first 2 missions
  3. 1 Executions of the first 3 missions
  4. 2 Executions of the first 2 missions
  5. 2 Executions of the first 3 missions
  6. 2 Executions of the first 1 missions
  7. 3 Executions of the first 3 missions
  8. 3 Executions of the first 1 missions
  9. 3 Executions of the first 2 missions
  10. 4 Executions of the first 3 missions
  11. 4 Executions of the first 2 missions
  12. 4 Executions of the first 1 missions
  13. 1 Executions of the first 4 missions
  14. 2 Executions of the first 4 missions
  15. 3 Executions of the first 4 missions
  16. 4 Executions of the first 4 missions

In the previous code, a fixed-size thread pool was created, with a capacity of 3, and then the loop performed 4 tasks, as shown by the output, the first 3 tasks were executed, and then the idle thread went to perform a 4th task, in Fixedthreadpool, there was a fixed-size pool, If the task currently needs to be performed exceeds the pool size, then more than the task waits until the idle thread executes the task, and when the task is less than the pool size, the idle thread is not destroyed .
2. Cachedthreadpool

The previous section of code is unchanged elsewhere, replacing the Newfixedthreadpool method with the Newcachedthreadpool method.

Output Result:

  1. 1 Executions of the first 3 missions
  2. 1 Executions of the first 4 missions
  3. 1 Executions of the first 1 missions
  4. 1 Executions of the first 2 missions
  5. 2 Executions of the first 4 missions
  6. 2 Executions of the first 3 missions
  7. 2 Executions of the first 2 missions
  8. 2 Executions of the first 1 missions
  9. 3 Executions of the first 2 missions
  10. 3 Executions of the first 3 missions
  11. 3 Executions of the first 1 missions
  12. 3 Executions of the first 4 missions
  13. 4 Executions of the first 2 missions
  14. 4 Executions of the first 4 missions
  15. 4 Executions of the first 3 missions
  16. 4 Executions of the first 1 missions

As can be seen, 4 tasks are performed alternately, Cachedthreadpool creates a buffer, caches the initialized thread, if the thread is available, uses the previously created thread, if it is not available, creates a new thread, Terminates and removes a thread that has not been used for 60 seconds from the cache .

3. Singlethreadexecutor

The previous section of code is unchanged elsewhere, replacing the Newfixedthreadpool method with the Newsinglethreadexecutor method.

Output Result:

  1. 1 Executions of the first 1 missions
  2. 2 Executions of the first 1 missions
  3. 3 Executions of the first 1 missions
  4. 4 Executions of the first 1 missions
  5. 1 Executions of the first 2 missions
  6. 2 Executions of the first 2 missions
  7. 3 Executions of the first 2 missions
  8. 4 Executions of the first 2 missions
  9. 1 Executions of the first 3 missions
  10. 2 Executions of the first 3 missions
  11. 3 Executions of the first 3 missions
  12. 4 Executions of the first 3 missions
  13. 1 Executions of the first 4 missions
  14. 2 Executions of the first 4 missions
  15. 3 Executions of the first 4 missions
  16. 4 Executions of the first 4 missions

4 tasks are executed sequentially,Singlethreadexecutor get a single thread, this thread will ensure that your task execution is completed, if the current thread terminates unexpectedly, a new thread will be created to continue the task , which is different from the thread we created directly. It is also different from Newfixedthreadpool (1).

4.ScheduledThreadPool

1 ImportJava.util.concurrent.ScheduledExecutorService; 2 ImportJava.util.concurrent.TimeUnit; 3  Public classThreadpooltest {4      Public Static voidMain (string[] args) {5Scheduledexecutorservice Schedulepool = Executors.newscheduledthreadpool (1); 6         //5 Seconds to execute the mission .7Schedulepool.schedule (NewRunnable () {8              Public voidrun () {9SYSTEM.OUT.PRINTLN ("Explosion"); Ten             }   One}, 5, Timeunit.seconds);  A         //perform a task in 5 seconds and execute once every 2 seconds -Schedulepool.scheduleatfixedrate (NewRunnable () { - @Override the              Public voidrun () { -SYSTEM.OUT.PRINTLN ("Explosion");  -             }   -}, 5, 2, Timeunit.seconds);  +     }   -}

Scheduledthreadpool can perform tasks on a timed or delayed basis.

Java's concurrency package is very powerful, the above is just the introduction, as the study in depth, there will be more records in the blog.

This article from: Gao | Coder, the original address: http://blog.csdn.net/ghsau/article/details/7443324, reprint please specify.

Java multi-thread 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.