Executors执行器newCachedThreadPool方法示例

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

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

Executors.newCachedThreadPool() 方法

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

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

  1. final ExecutorService executorService = Executors.newCachedThreadPool();

Executors.newCachedThreadPool() 方法示例

  1. import java.util.concurrent.ExecutionException;
  2. import java.util.concurrent.ExecutorService;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.TimeUnit;
  5. public class CachedThreadPoolExample {
  6. public static void main(final String[] args) throws InterruptedException, ExecutionException {
  7. System.out.println("Thread main started");
  8. Runnable task1 = () -> {
  9. System.out.println("Executing Task1 inside : " + Thread.currentThread().getName());
  10. try {
  11. TimeUnit.SECONDS.sleep(2);
  12. } catch (InterruptedException ex) {
  13. throw new IllegalStateException(ex);
  14. }
  15. };
  16. Runnable task2 = () -> {
  17. System.out.println("Executing Task2 inside : " + Thread.currentThread().getName());
  18. try {
  19. TimeUnit.SECONDS.sleep(4);
  20. } catch (InterruptedException ex) {
  21. throw new IllegalStateException(ex);
  22. }
  23. };
  24. Runnable task3 = () -> {
  25. System.out.println("Executing Task3 inside : " + Thread.currentThread().getName());
  26. try {
  27. TimeUnit.SECONDS.sleep(3);
  28. } catch (InterruptedException ex) {
  29. throw new IllegalStateException(ex);
  30. }
  31. };
  32. final ExecutorService executorService = Executors.newCachedThreadPool();
  33. System.out.println("Submitting the tasks for execution...");
  34. executorService.submit(task1);
  35. executorService.submit(task2);
  36. executorService.submit(task3);
  37. executorService.shutdown();
  38. System.out.println("Thread main finished");
  39. }
  40. }

输出

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

相关文章