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.
We explain in detail why we use the thread pool? ( program Optimization )
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.
--runnable interface using thread pool mode
Typically, the thread pool is created through the thread pool factory, then calls the methods in the thread pool to get the thread, and then executes the task method through the threads.
L executors: thread pool Create factory class
n public static Executorservice newfixedthreadpool (int nthreads): Returns the thread pool object
L executorservice: thread pool class
N future<?> submit(Runnable Task): Gets a thread object in the thread pool and executes
L Future Interface : used to record the results of a thread task after it has been executed. Thread pool creation and use
To use thread-pooling threads in the process object:
n Creating a thread pool object
N Create runnable interface subclass object (Create Task)
N Commit runnable Interface subclass object (perform Task)
n Close the thread pool
Code Demo:
public class ThreadPoolDemo {
public static void Main (string[] args) {
//Create thread pool object
Executorservice service = Executors.newfixedthreadpool (2); //contains 2 thread objects
//Create runnable instance Object
myrunnable r = new Myrunnable ();
How to create a thread object yourself
Thread t = new Thread (r);
T.start (); ---> Call run () in myrunnable
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
Close the thread pool
Service.shutdown ();
}
}
L Runnable Interface Implementation class
public class Myrunnable implements Runnable {
@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("I want a Coach");
try {
Thread.Sleep (2000);
} catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println ("Coach came:" +thread.currentthread (). GetName ());
System.out.println ("Teach me to swim, after hand, coach back to the swimming pool");
}
}
-callable interface using thread pool mode (dedicated to thread pool)
L 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 to set the return value .
L executorservice: thread pool class
n <T> future<t> Submit(callable<t> Task): Gets a thread object in the thread pool and executes the call () method in the thread
L Future Interface : used to record the results of a thread task after it has been executed . Thread pool creation and use
To use thread-pooling threads in the process object:
n Creating a thread pool object
N Creating an Callable interface subclass object
N commits the callable interface subclass Object
n Close the thread pool
Code Demo:
public class ThreadPoolDemo {
public static void Main (string[] args) {
To create a thread pool object
Executorservice service = Executors.newfixedthreadpool (2);//contains 2 thread objects
Create a Callable Object
mycallable C = new mycallable ();
Gets the thread object from the thread pool, and then calls the run () in the myrunnable
Service.submit (c);
And get a coach.
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 ();
}
}
L Callable Interface implementation class, the call method throws an exception, returns the result after the thread task has finished executing
public class Mycallable implements callable {
@Override
public Object call () throws Exception {
SYSTEM.OUT.PRINTLN ("I want a coach: Call");
Thread.Sleep (2000);
System.out.println ("Coach came:" +thread.currentthread (). GetName ());
System.out.println ("Teach me to swim, after hand, coach back to the swimming pool");
return null;
}
}
thread Pool Exercise: Returns the result of adding two numbers
Requirement: Complete two number sum operation using callable interface through thread object in thread pool
L Future Interface : used to record the results of a thread task after it has been executed.
n V get () Gets the data results encapsulated in the future object
Code Demo:
public class ThreadPoolDemo {
public static void Main (string[] args) throws Interruptedexception, Executionexception {
To create a thread pool object
Executorservice ThreadPool = Executors.newfixedthreadpool (2);
Create a callable interface subclass object
Mycallable C = new mycallable ();
Mycallable C = new mycallable (100, 200);
mycallable C2 = new Mycallable (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 object
future<integer> result = Threadpool.submit (c);
The result type returned by the Get method for this future
Integer sum = Result.get ();
System.out.println ("sum=" + sum);
Re-demo
result = Threadpool.submit (C2);
sum = Result.get ();
System.out.println ("sum=" + sum);
}
}
L Callable Interface Implementation class
public class Mycallable implements callable<Integer> {
Member variables
int x = 5;
int y = 3;
Construction method
Public mycallable () {
}
public mycallable (int x, int y) {
this.x = x;
This.y = y;
}
@Override
Public Integer Call () throws Exception {
return x+y;
}
}
Multithreaded _ thread pool Java