Using ExecutorService based on JUC thread pool
The purpose of multithreading is often to improve program efficiency and improve system usability. But the frequent creation and destruction of threads is itself a detrimental thing. So Java's JUC provides the use of thread pools.
Thread pool: Create multiple threads in advance and put them into the thread pool, get them directly when using them, and put them back into the thread pool after using them. It can avoid the frequent creation and destruction of threads and realize reuse.
benefit:
- Improved response efficiency (reduce thread creation time)
- Reduce resource consumption (reuse threads in the thread pool, no longer create)
- Easy to manage.
corePoolSize: core pool size
maximumPoolSize: maximum number of threads
keepAliveTime: how long the thread will stop after it has no tasks
JDK5.0 provides related thread pool APIs: Executors and ExecutorService
The real thread pool interface of ExecutorService inherits the
common implementation class ThreadPoolExecurtor of Executor .
- void executor (Runable runable) The thread pool starts the thread. (Belonging to Executor class method)
- void shutdown() Close the connection pool (ExecutorService interface method)
Executors tool class, thread pool factory class, used to create and return different types of thread pools. Pay attention to distinguish Executor
Implementation steps
- Create thread pool service
- Thread of execution
achieve:
// 线程类
static class ThreadTest implements Runnable{
public void run() {
System.out.println(Thread.currentThread().getName()+":执行了");
}
}
// 执行类
public static void main(String[] args) {
// 创建线程服务,构造线程池为3
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 启动线程
executorService.execute(new ThreadTest());
executorService.execute(new ThreadTest());
executorService.execute(new ThreadTest());
executorService.execute(new ThreadTest());
}
Result: The thread pool is defined as 3, then 4 threads use 3 threads in the thread pool.