我有一个List<Map<String,String>>的地图列表。每个Map都将File Name作为Key,将File Content作为Value。
我在上面的列表中有超过25个Lakh地图。我的要求是遍历这个列表,并在读取每个Map键和值的输出文件夹中创建Files。所以在结束时,我将有25lakh文件。这需要4个多小时。然后我停止这个程序。我不知道确切的时间,如果我运行整个25lakh记录的程序。
我需要使用多线程来优化它。
我如何使用Java Executors/ Fork/ Join (我有Java 7)来优化它
发布于 2013-04-11 03:35:17
如果你在一张磁盘上写你的文件,我不认为添加更多的线程会有真正的帮助。您的程序是IO密集型的,而不是CPU密集型的。
发布于 2013-04-11 03:36:13
您可以使用一个ThreadPoolExecutor和一个实现Runnable的类。
public class Processor implements Runnable {
private final Map<String, String> map;
public Processor(Map<String, String> map) {
this.map = map;
}
public void run() {
// Do work here
}
}
ThreadPoolExecutor executor = new ThreadPoolExecutor();
for(Map<String, String> map : list) {
executor.execute(new Processor(map));
}发布于 2013-04-11 03:37:40
并行化可以通过将问题分成与处理器可用一样多的子问题来实现。对于列表迭代器,您可以迭代子列表:
int nThreads = Runtime.getRuntime().availableProcessors() + 1;
ExecutorService exec = Executors.newFixedThreadPool( nThreads );
int interval = list.size()/parallel.nThreads;
int from = 0;
for( int i = 0; i < nThreads; ++i ) {
int to = ( i == nThreads - 1 ) ? 1000 : from + interval;
exec.submit( new Search( from, to, list ));
from = to;
}
exec.shutdown();
exec.awaitTermination( 1, TimeUnit.DAYS );类Search用于完成这项工作(创建文件)。
Search类示例:
class Search implements Runnable {
final int from;
final int to;
final List< Map< String, String >> list;
Search( int from, int to, List< Map< String, String >> list ) {
this.from = from;
this.to = to;
this.list = list;
}
@Override
public void run(){
for( int b = from; b < to; ++b ) {
Map< String, String > map = list.get(b);
...
}
}
}https://stackoverflow.com/questions/15934727
复制相似问题