Next (second) Java Multithreaded Programming Basics Tutorial

Source: Internet
Author: User

6. Using Thread pool Executeservice

The thread pool provides a solution for threading life-cycle overhead problems and resource shortages. By reusing threads on multiple tasks, the cost of thread creation is distributed across multiple tasks. The benefit is that because the thread already exists when the request arrives, it inadvertently eliminates the delay caused by thread creation. This allows the service to be requested immediately, making the application more responsive. Also, by properly sizing the number of threads in the thread pool, that is, when the number of requests exceeds a certain threshold, you can force any other new requests to wait until a thread is available to process the location, preventing the resource from running out of resources.

The thread pool is a high-level technique for managing threads, and it usually provides several features like

    • Through the management of the thread, more reasonable allocation of resources. Typically, the line constructor maintains a set of idle threads and provides out-of-the-way to dynamically increase or decrease the number of idle threads depending on how busy the system is. The more advanced features that automatically detect exceptions are also available.

    • By maintaining the existing threads in the thread pool, you can save the overhead of creating threads, especially for programs with frequent processing such as webserver and faster processes, and the overhead of creating threads cannot be ignored.

Java.util.concurrent provides mutual exclusion, semaphores, collection classes such as queues and hashes that perform well under concurrent access, and several task queue implementations. The Excutors class in the package is an effective, widely used, and correctly implemented thread pool that is based on the task force. There is no need for individuals to attempt to write their own thread pool, which is prone to error.

The thread pool is created simply by using the Excutors.newfixedthreadpool (i) function to create a thread pool of size I, and the instance belongs to the Executorservice type. You can then call the Execute () function of the class to start a thread, and the input parameter is a variable of the thread.

The following is a simple example of using a 2-size thread pool to process 100 threads.

Note: The thread pool must use shutdown to display the shutdown or the main thread cannot exit.

Shutdown does not block the main thread

package org.test.thread;import  java.util.concurrent.executorservice;import java.util.concurrent.executors;/** *  @author   Administrator * * uses two thread pools to process 100 threads  *  */public class testexecuteservice  {public static void main (String[] args)  {ExecutorService exec =  Executors.newfixedthreadpool (2); for (int i = 0;i < 100;i++) {//define an inner class runnable  Run = new runnable ()  {@Overridepublic  void run ()  {// TODO  auto-generated method stublong time =  (Long)   (Math.random ()  * 1000); System.out.println ("Hibernate" +time); Try {thread.sleep (time);}  catch  (interruptedexception e)  {e.printstacktrace ();}}; Exec.execute (run);} The thread pool must be closed Exec.shutdown ();}} 

during the loop , there are idle threads in the waiting thread pool, so the main thread is blocked, in order to solve this problem, it is common to start a thread to do the for loop, in order to avoid blocking the main thread because the thread pool is full. The code looks like this:

package org.test.thread;import java.util.concurrent.executorservice;import  java.util.concurrent.executors;/** *  @author  administrator * * uses two thread pools to process 100 threads  * /public class testexecuteservice {public static void main (String[] args)  {new testexecuteservice (). Testexec (2,100); New testexecuteservice (). Testforexec (2,100); /** *  may occur thread blocking  * */private void testexec (int poolsize,int threadsize)  {executorservice exec = executors.newfixedthreadpool (poolsize); for (int i =  0;i < threadsize;i++) {//define an inner class runnable run = new runnable ()  {@ Overridepublic void run ()  {// todo auto-generated method stublong time  =  (Long)   (Math.random ()  * 1000); System.out.println ("Hibernate" +time); Try {thread.sleep (time);}  catch  (INTERRUPTEDEXCEPTION&Nbsp;e)  {e.printstacktrace ();}}; Exec.execute (run);} The thread pool must be closed Exec.shutdown ();} /** *  uses a thread to process the For loop  * */private void testforexec (Final int poolsize, Final int threadsize) {//Create inner class class test extends thread{@Overridepublic  void  run ()  {executorservice exec = executors.newfixedthreadpool (poolSize);for  (int  i = 0; i < threadsize; i++)  {//defines an inner class runnable run =  new runnable ()  {@Overridepublic  void run ()  {// todo auto-generated  method stublong time =  (Long)   (Math.random ()  * 1000); System.out.println ("Hibernate  " +time); Try {thread.sleep (time);}  catch  (interruptedexception e)  {e.printstacktrace ();}}; Exec.execute (run);} Must show shutdown thread pool Exec.shutdown ();}} New test (). Start ();}}

When we write a socket-based server program, it is common practice for each client to create a new thread for it, and the client to leave before destroying the thread. However, if multiple threads are created frequently and destroyed, there is a significant waste of system resources. However, the use of thread pooling technology can greatly reduce the number of program creation and destruction, and improve the efficiency of the server.





This article is from the "Ah Cool blog source" blog, please make sure to keep this source http://aku28907.blog.51cto.com/5668513/1773073

Next (second) Java Multithreaded Programming Basics Tutorial

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.