Executors执行器newCachedThreadPool方法示例

x33g5p2x  于2022-10-06 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(329)

在这篇文章中,我们将学习Executor的newCachedThreadPoolfactory方法。

Executors.newCachedThreadPool() 方法

这个方法创建了一个线程池,它可以根据需要创建新的线程,但是当之前构建的线程可用时,会重新使用。这些线程池通常会提高执行许多短暂的异步任务的程序的性能。

对执行的调用将重用先前构建的线程,如果可用的话。如果没有现有的线程可用,将创建一个新的线程并添加到池中。六十秒内未被使用的线程将被终止并从缓存中删除。因此,一个池子如果保持足够长的空闲时间,就不会消耗任何资源。注意,具有类似属性但细节不同(例如超时参数)的池可以使用ThreadPoolExecutorconstructors创建。
语法。

final ExecutorService executorService = Executors.newCachedThreadPool();

Executors.newCachedThreadPool() 方法示例

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class CachedThreadPoolExample {

    public static void main(final String[] args) throws InterruptedException, ExecutionException {

        System.out.println("Thread main started");

        Runnable task1 = () -> {
             System.out.println("Executing Task1 inside : " + Thread.currentThread().getName());
             try {
                  TimeUnit.SECONDS.sleep(2);
             } catch (InterruptedException ex) {
                  throw new IllegalStateException(ex);
             }
        };

        Runnable task2 = () -> {
             System.out.println("Executing Task2 inside : " + Thread.currentThread().getName());
             try {
                  TimeUnit.SECONDS.sleep(4);
             } catch (InterruptedException ex) {
                  throw new IllegalStateException(ex);
             }
       };

        Runnable task3 = () -> {
            System.out.println("Executing Task3 inside : " + Thread.currentThread().getName());
            try {
                 TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException ex) {
                 throw new IllegalStateException(ex);
            }
        };

        final ExecutorService executorService = Executors.newCachedThreadPool();
        System.out.println("Submitting the tasks for execution...");
        executorService.submit(task1);
        executorService.submit(task2);
        executorService.submit(task3);

        executorService.shutdown();

        System.out.println("Thread main finished");
    }
}

输出

Thread main started
Submitting the tasks for execution...
Executing Task1 inside : pool-1-thread-1
Executing Task3 inside : pool-1-thread-3
Executing Task2 inside : pool-1-thread-2
Thread main finished

相关文章

微信公众号

最新文章

更多