第六章 Java newCachedThreadPool 示例


在本教程中,我们将学习 Executor 的 newCachedThreadPool 工厂方法。 在上一篇教程中,我分享了 ThreadPoolExecutor 的介绍。如果您不了解 ThreadPoolExecutor 的概念,您应该先了解一下。

Executor 的 newCachedThreadPool 工厂方法:

此方法返回一个无界线程池。它将最大池大小设置为 Integer.Max,它将根据需要创建新线程。如果需求减少,如果线程空闲超过 1 分钟,它将关闭线程。

例子:

让我们创建一个任务。这里的任务是读取不同的文件并处理它们。

package org.arpit.java2blog.bean;

public class FetchDataFromFile implements Runnable{

private final String fileName;

public FetchDataFromFile(String fileName) {
super();
this.fileName = fileName;
}

@Override
public void run() {
try {
System.out.println("Fetching data from "+fileName+" by "+Thread.currentThread().getName());
Thread.sleep(5000); // Reading file
System.out.println("Read file successfully: "+fileName+" by "+Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String getFileName() {
return fileName;
}
}

让我们创建 ThreadPoolExecutor 它将消耗上述任务并处理它。

package org.arpit.java2blog;

import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

public class ThreadPoolExecutorMain {
public static void main(String args[]) {
   // Getting instance of ThreadPoolExecutor using  Executors.newCachedThreadPool factory method
  ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

  for (int i = 1; i <= 10; i++) {
   FetchDataFromFile fdff = new FetchDataFromFile("File :" + i);
   System.out.println("A new file has been added to read : " + fdff.getFileName());
   threadPoolExecutor.execute(fdff);
  }
  threadPoolExecutor.shutdown();
}
}

当你运行上面的程序时,你会得到下面的输出:

A new file has been added to read : File :1
A new file has been added to read : File :2
Fetching data from File :1 by pool-1-thread-1
Fetching data from File :2 by pool-1-thread-2
A new file has been added to read : File :3
A new file has been added to read : File :4
Fetching data from File :3 by pool-1-thread-3
Fetching data from File :4 by pool-1-thread-4
A new file has been added to read : File :5
Fetching data from File :5 by pool-1-thread-5
A new file has been added to read : File :6
Fetching data from File :6 by pool-1-thread-6
A new file has been added to read : File :7
Fetching data from File :7 by pool-1-thread-7
A new file has been added to read : File :8
A new file has been added to read : File :9
Fetching data from File :8 by pool-1-thread-8
A new file has been added to read : File :10
Fetching data from File :9 by pool-1-thread-9
Fetching data from File :10 by pool-1-thread-10

如果你注意到,我们已经提交了 10 个任务,它根据需求创建了 10 个新线程。如果任何线程空闲超过一分钟,它就会将其拆除。当您想要比 newFixedThreadPool 更好的排队性能时,newCachedThreadPool 是一个不错的选择。如果要限制资源管理的并发任务数,请使用 newFixedThreadPool。


原文链接:https://codingdict.com/