Home  >  Article  >  Java  >  Four ways to create a thread pool in Java

Four ways to create a thread pool in Java

Guanhui
GuanhuiOriginal
2020-06-04 09:29:324990browse

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<Runnable>());
    }

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<Runnable>());
    }

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

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);
                }
            });
        }
    }
}

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!

Statement:
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