00101_ thread Pool

Source: Internet
Author: User

1. Thread pool Concept

(1) The thread pool, in fact, is a container that accommodates multiple threads, where threads can be reused, eliminating the need to create thread objects frequently and consuming excessive resources without having to create threads repeatedly;

(2) Why use a thread pool?

① in Java, it is quite expensive to create a new thread if each request arrives. In practice, creating and destroying threads takes a considerable amount of time and system resources, and may even be more than the time and resources required to process the actual user requests, and in addition to the overhead of creating and destroying threads, the active thread consumes system resources;

② If you create too many threads in one JVM, you may cause the system to be out of resources due to excessive memory consumption or "over-switching";

③ in order to prevent resource shortages, there are some ways to limit the number of requests processed at any given moment, minimizing the number of threads created and destroyed, especially the creation and destruction of threads that consume relatively large amounts of resources, and using existing objects as far as possible to service them;

The ④ thread pool is primarily used to address thread life-cycle overhead and resource-poor issues. By reusing threads for multiple tasks, the overhead of thread creation is distributed across multiple tasks, and the delay caused by thread creation is eliminated because the thread already exists when the request arrives. In this way, you can immediately service the request and use the application to respond faster. In addition, the lack of resources can be prevented by adjusting the number of threads in the thread appropriately.

2. Using thread pool mode--runnable interface

(1) In general, thread pool is created through the thread pool factory, then calls the thread pool method to get the thread, then through the thread to execute the task method;

(2) Executors: thread pool to create factory class;

(3) Executorservice: Thread pool class;

(4) Future interface: Used to record the results of the execution of a thread task. Thread pool creation and use;

(5) Code Demo:

①runnable interface Implementation Class

1  Public classMyrunnableImplementsRunnable {2 @Override3      Public voidrun () {4SYSTEM.OUT.PRINTLN ("I want a Coach");5 6         Try {7Thread.Sleep (2000);8}Catch(interruptedexception e) {9 e.printstacktrace ();Ten         } OneSystem.out.println ("The coach has come:" +Thread.CurrentThread (). GetName ()); ASystem.out.println ("Teach me to swim, after hand, coach back to the pool.")); -     } -}

② Test class

1 ImportJava.util.concurrent.ExecutorService;2 Importjava.util.concurrent.Executors;3 4  Public classThreadPoolDemo {5      Public Static voidMain (string[] args) {6         //To create a thread pool object7Executorservice service = Executors.newfixedthreadpool (2);//contains 2 thread objects8         //Creating an Runnable instance Object9Myrunnable r =Newmyrunnable ();Ten  One         //How to create a thread object yourself A         //thread t = new Thread (r); -         //T.start ();---> Call run () in Myrunnable -  the         //gets the thread object from the thread pool, and then calls the run () in the myrunnable - Service.submit (r); -         //fetch a Thread object again, call the Run () in Myrunnable - Service.submit (r); + Service.submit (r); -         //Note: After the Submit method call ends, the program does not terminate because the thread pool controls the shutdown of the threads. Returning the used thread to the thread pool +  A         //Close the thread pool at         //Service.shutdown (); -     }callable Interface Implementation class, the call method throws an exception and returns the result after the thread task has finished executing}

3. Using thread pool mode-callable interface

(1) Callable interface: Similar to the runnable interface function, used to specify the task of the thread. The call () method, which returns the result of the completion of the thread task, can throw an exception;

(2) Executorservice: Thread pool class;

(3) Future interface: Used to record the results of the execution of a thread task. Thread pool creation and use;

(4) To use thread pooling threads:

① creating a thread pool object;

② Create callable interface subclass object;

③ commits the callable interface subclass object;

④ closes the thread pool.

(5) Code Demo:

①callable interface implementation class, the call method throws an exception and returns the result after the thread task has finished executing

1 Importjava.util.concurrent.Callable;2 3  Public classMycallableImplementsCallable {4 @Override5      PublicObject Call ()throwsException {6SYSTEM.OUT.PRINTLN ("I want a coach: Call");7Thread.Sleep (2000);8System.out.println ("The coach has come:" +Thread.CurrentThread (). GetName ());9System.out.println ("Teach me to swim, after hand, coach back to the pool."));Ten         return NULL; One     } A}

② Test class

1 ImportJava.util.concurrent.ExecutorService;2 Importjava.util.concurrent.Executors;3 4  Public classThreadPoolDemo2 {5      Public Static voidMain (string[] args) {6         //To create a thread pool object7Executorservice service = Executors.newfixedthreadpool (2);//contains 2 thread objects8         //Create a Callable object9Mycallable C =Newmycallable ();Ten  One         //gets the thread object from the thread pool, and then calls the run () in the myrunnable A Service.submit (c); -  -         //and get a coach . the Service.submit (c); - Service.submit (c); -         //Note: After the Submit method call ends, the program does not terminate because the thread pool controls the shutdown of the threads. Returning the used thread to the thread pool -  +         //Close the thread pool -         //Service.shutdown (); +     } A}

00101_ 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.