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

What are the four thread pools in Java Executors

王林
Release: 2023-05-14 18:01:06
forward
1593 people have browsed it

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();
 
        }
 
        }
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template