background:
Resources that are frequently created and destroyed and use a large amount of resources, such as threads under concurrent conditions, have a great impact on performance.
Ideas:
Create multiple threads in advance, put them into the thread pool, obtain them directly when using them, and put them back into the pool after use. It can avoid frequent creation and destruction and achieve reuse. Similar to public transportation in life.
benefit:
1. Improve response speed (reduce the time to create new threads)
2. Reduce resource consumption (reuse threads in the thread pool, do not need to create each time)
3. Easy thread management
corePoolSize: the size of the core pool
maximumPoolSize: maximum number of threads
keepAliveTime: When the thread has no tasks, it will be terminated after how long it will keep at most
…
Thread pool related API
JDK 5.0 provides thread pool related API : ExecutorService and Executors
ExecutorService : The real thread pool interface. Common subclass ThreadPoolExecutor
void execute(Runnable command): execute task/command, no return value, generally used to execute Runnable
Future submit(Callable task): Execute the task, have a return value, and generally execute the Callable
void shutdown() : close the connection pool
Executors: Tool classes, factory classes for thread pools, used to create and return different types of thread pools
Executors.newCachedThreadPool(): Creates a thread pool that can create new threads as needed
Executors.newFixedThreadPool(n); Create a thread pool with a fixed number of threads that can be reused
Executors.newSingleThreadExecutor() : Create a thread pool with only one thread
Executors.newScheduledThreadPool(n): Creates a thread pool that can be scheduled to run commands after a given delay or periodically.
=========================================================================
step:
1. Provide a thread pool with a specified number of threads. 2. Execute the operation of the specified thread. It is necessary to provide an object that implements the Runnable interface Callable interface implementation class 3. Close the connection pool
=========================================================================
Take "traversing even numbers within 1-100" as an example
code show as below:
class NumberThread implements Runnable{
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
if (i % 2 == 0){
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}
}
public class ThreadPool {
public static void main(String[] args) {
//1.提供指定线程数量的线程池
ExecutorService service = Executors.newFixedThreadPool(10);
//2.执行指定的线程的操作。需要提供实现Runnable接口Callable接口实现类的对象
service.execute(new NumberThread());//适合适用于Runnable
//service.submit(Callable callable);//适合适用于Callable
//3.关闭连接池
service.shutdown();
}
}
thanks for watching! ! !