Home  >  Article  >  Java  >  What are the four thread pools in Java Executors

What are the four thread pools in Java Executors

王林
王林forward
2023-05-14 18:01:061562browse

1. Thread pool description

newCachedThreadPool creates a cache thread pool. If the length of the thread pool exceeds processing needs, idle threads can be flexibly recycled. If they cannot be recycled, new ones can be created. the rout.

newFixedThreadPool creates a fixed-length thread pool, which can control the number of concurrent threads. Exceeding threads wait in the queue.

newScheduledThreadPool establishes a fixed long-term thread pool to support the execution of scheduled and periodic tasks.

newSingleThreadExecutor creates a single-threaded thread pool that can only use a unique worker thread to execute tasks, ensuring that all tasks are executed in the specified order.

2. Example

class ThreadDemo extends Thread {
 
    @Override
 
    public void run() {
 
        System.out.println(Thread.currentThread().getName() + "正在执行");
 
    }
 
}
 
class TestFixedThreadPool {
 
        public static void main(String[] args) {
 
        //创建一个可重用固定线程数的线程池
 
        ExecutorService pool = Executors.newFixedThreadPool(2);
 
        //创建实现了Runnable接口对象,Thread对象当然也实现了Runnable接口
 
        Thread t1 = new ThreadDemo();
 
        Thread t2 = new ThreadDemo();
 
        Thread t3 = new ThreadDemo();
 
        Thread t4 = new ThreadDemo();
 
        Thread t5 = new ThreadDemo();
 
        //将线程放入池中进行执行
 
        pool.execute(t1);
 
        pool.execute(t2);
 
        pool.execute(t3);
 
        pool.execute(t4);
 
        pool.execute(t5);
 
        //关闭线程池
 
        pool.shutdown();
 
        }
 
        }

The above is the detailed content of What are the four thread pools in Java Executors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete