可以通过将问题拆分为与可用处理器一样多的子问题来实现并行化。对于列表迭代器,您可以迭代子列表:
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);
...
}
}
}