1. Thread pool Concept
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.
Why use a thread pool?
in Java, it is quite expensive to create a new thread if each request arrives. In practice, the time spent creating and destroying threads and the amount of system resources consumed are quite large, and may even be more than the time and resources required to process actual user requests. In addition to the overhead of creating and destroying threads, the active thread also consumes system resources. If you create too many threads in a single JVM , you may cause your system to be running out of resources due to excessive memory consumption or "over-switching". To prevent resource shortages, there are ways to limit the number of requests processed at any given moment, minimizing the number of threads that are created and destroyed, especially if some of the resources are expensive to create and destroy, and use existing objects to service them as much as possible.
Thread pooling 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
The thread pool is created through the thread pool factory, calls the methods in the thread pools to get the thread, and then executes the task method through the thread.
1. Executors: Thread pool Create factory class
// returns the thread pool object, Newfixedthreadpool () method, int indicates the number of threads created Public Static Executorservice newfixedthreadpool (int nthreads):
2, Executorservice: Thread pool class
// gets a thread object in the thread pool, and executes the Future<?> Submit (Runnable Task):
3. Future interface: Used to record the results of thread task execution. Thread pool creation and use
4. To use thread-pooling threads for the process object:
- To create a thread pool object
- Create Runnable interface sub-class object
- Submit Runnable interface sub-class object
- Close the thread pool
3. code example
Runnable interface Implementation Class
Public class Implements Runnable {// override Run () method Public void run () { for (int i = 0; i < i++) { System.out.println ("Run ..... "+i);} } }
Create a thread pool, and extract threads to execute
Public classDemo01 { Public Static voidMain (string[] args) {//gets the thread pool object (obtained from the thread pool Factory), 2 represents two threadsExecutorservice es= Executors.newfixedthreadpool (2); //Creating an Runable instance ObjectMyrunnable run=Newmyrunnable (); //commits the Runnable interface subclass object and executesEs.submit (run); for(inti = 0; I < 50; i++) {System.out.println ("Main ..." +i); } //Close the thread poolEs.shutdown (); }}3. Using thread pool mode-callableInterface
Callable Interface : similar to the Runnable interface function, used to specify a thread's task. The call () method, which returns the result of the completion of the thread task, throws an exception.
1, Executorservice: Thread pool class
// gets a thread object in the thread pool and executes the call () method in the thread <T> future<t> submit (callable<t> Task):
2. Future interface: Used to record the results of thread task execution. Thread pool creation and use
3. To use thread-pooling threads for the process object:
- To create a thread pool object
- Create Callable interface sub-class object
- Submit Callable interface sub-class object
4. code example
Callable interface implementation class, the call method throws an exception and returns the result after the thread task has finished executing
Public class Implements Callable<string> { // callable Generic is the return value type of your call () method // override Call () method public throws Exception { return "This is the call method"; }}
Creates a thread pool, extracts threads, and executes
Public classDemo02 { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {//get thread pool methodExecutorservice es= Executors.newfixedthreadpool (2); //Create a callable subclassMycallable mc=Newmycallable (); //Submit callable SubclassFuture<string> f=Es.submit (MC); String Str=F.get (); System.out.println (str); //Close the thread poolEs.shutdown (); }}5. Thread pool Exercise: Returns the result of two numbers added
requirement: Through thread objects in the thread pool, use the Callable Interface completes two number sum operation
Lfuture interface: Used to record the results of a thread task after it has been executed. Thread pool creation and use
Get () Gets the data results encapsulated in the future object
Code Demo:
Public classThreadPoolDemo { Public Static voidMain (string[] args)throwsinterruptedexception, executionexception {//To create a thread pool objectExecutorservice ThreadPool = Executors.newfixedthreadpool (2); //Create a callable interface subclass object and assign a value//mycallable C = new mycallable ();Mycallable C =NewMycallable (100, 200); Mycallable C2=NewMycallable (10, 20); //gets the thread in the thread pool, calls the call () method in the callable interface subclass object, and completes the sum operation//<Integer> future<integer> Submit (callable<integer> Task)//Future Result Objectfuture<integer> result =Threadpool.submit (c); //The result type returned by the Get method for this futureInteger sum =Result.get (); System.out.println ("Sum=" +sum); //Re-demoresult =threadpool.submit (C2); Sum=Result.get (); System.out.println ("Sum=" +sum); //Close thread pool (can not be closed)Threadpool.shutdown (); }}
Callable Interface Implementation Class
Public classMycallableImplementsCallable<integer> { //member Variables intx = 5; inty = 3; //Construction Method Publicmycallable () {} PublicMycallable (intXinty) { This. x =x; This. y =y; } @Override PublicInteger Call ()throwsException {returnx+y; }}
Understand the concepts, examples, and usages of Factory mode, proxy mode, singleton mode
Java thread--thread pool