Java NewCachedThreadPool示例
时间:2020-02-23 14:35:05 来源:igfitidea点击:
在本教程中,我们将了解executor的newcachedthreadpool工厂方法。
在最后一个教程中,我已经共享了ThreadPoolExecutor的简介。
如果我们不了解ThreadPoolExecutor的概念,则应首先通过它。
executor的newcachedthreadpool工厂方法:
此方法返回一个无限的线程池。
它将最大池大小设置为Integer.max,它将根据需求创建新线程。
如果需求减少,如果线程空转超过1分钟,它将撕下线程。
例子:
让我们创建一项任务。
此处任务将是读取不同的文件并处理它们。
package org.igi.theitroad.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.igi.theitroad;
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。

