Thread Pool
- corePoolSize: The size of the core pool
- maximumPoolSize: maximum number of threads
- keepAliveTime: How long the thread will keep alive when there is no task before it will be terminated
- JDK5.0 provides thread pool related APIs: ExecutorService and Executors
- ExecutorService: The real thread pool interface. Common subclasses of ThreadPoolExecutor
- void execute(Runnable command) : Execute task/command, no return value, generally used to execute Runnable
- Futuresubmit(Callabletask): Execute the task, have a return value, and generally execute Callable again
- void shutdown(): closes the connection pool
- Executors: tool class, thread pool factory class, used to create and return different types of thread pools
Use thread pool
package com.senior;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
// 测试线程池
public class TestPool {
public static void main(String[] args) {
// 1.创建服务,创建线程池
// newFixedThreadPool:参数为线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
// 执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
// 2.关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}