Home > Java > Java Tutorial > body text

Four ways to create a thread pool in Java

Guanhui
Release: 2020-06-04 09:29:32
Original
4791 people have browsed it

Four ways to create a thread pool in Java

Four ways to create a thread pool in Java

1. newCachedThreadPool creates a cacheable thread pool. If the thread pool length exceeds processing needs, Idle threads can be flexibly recycled. If no threads can be recycled, new threads will be created.

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

3. newScheduledThreadPool creates a fixed-length thread pool to support scheduled and periodic task execution.

4. newSingleThreadExecutor creates a single-threaded thread pool. It will only use a unique working thread to execute tasks, ensuring that all tasks are executed in the specified order (FIFO, LIFO, priority).

newCachedThreadPool

Create a cacheable thread pool. If the length of the thread pool exceeds processing needs, idle threads can be flexibly recycled.

If there is no recycling , then create a new thread.

package cn.qbz.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test111907 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "   i=" + temp);
                }
            });
        }
    }
}
    public static ExecutorService newCachedThreadPool() {
        return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                      60L, TimeUnit.SECONDS,
                                      new SynchronousQueue());
    }
Copy after login

newFixedThreadPool

Create a fixed-length thread pool that can control the maximum number of concurrent threads. Exceeding threads will wait in the queue.

package cn.qbz.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test111907 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "   i=" + temp);
                }
            });
        }
    }
}
    public static ExecutorService newFixedThreadPool(int nThreads) {
        return new ThreadPoolExecutor(nThreads, nThreads,
                                      0L, TimeUnit.MILLISECONDS,
                                      new LinkedBlockingQueue());
    }
Copy after login

newScheduledThreadPool

Create a fixed-length thread pool to support scheduled and periodic task execution.

package cn.qbz.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test111907 {
    public static void main(String[] args) {
        final long begin = System.currentTimeMillis();
        ExecutorService executorService = Executors.newScheduledThreadPool(3);
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            final long time = begin;
            executorService.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "   i=" + temp + "   time=" + (System.currentTimeMillis() - time));
                }
            }, 5, TimeUnit.SECONDS);
        }
    }
}
    public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
        return new ScheduledThreadPoolExecutor(corePoolSize);
    }
    public ScheduledThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, Integer.MAX_VALUE, 0, TimeUnit.NANOSECONDS,
              new DelayedWorkQueue());
    }
Copy after login

newSingleThreadExecutor

Create a single-threaded thread pool, which will only use the only worker thread to execute tasks,

ensures that all tasks Execute in the specified order (FIFO, LIFO, priority).

package cn.qbz.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test111907 {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 10; i++) {
            final int temp = i;
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "   i=" + temp);
                }
            });
        }
    }
}
Copy after login

Recommended tutorial: Java Tutorial

The above is the detailed content of Four ways to create a thread pool in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!