【发布时间】:2018-09-30 21:05:22
【问题描述】:
我是线程新手,想知道是否可以使用线程将大量数据拆分为小任务,从而减少处理时间 我已将 Set 拆分为多个集合列表,并且来自执行程序服务的每个线程占用该集合并将该集合添加到另一个集合(全局声明)abcSet。 我需要每个线程将对象添加到该集合中,并且在所有线程完成添加后,继续使用 abcSet 完成的其余工作 下面是示例代码。请帮忙!!
private static final int PARTITIONS_COUNT = 4;
final Set<Abc> newAbcSet = new HashSet<Abc>();
final Set<Abc> abcSet = //data from database
ExecutorService e = Executors.newFixedThreadPool(4);
List<Set<Abc>> theSets = new ArrayList<Set<Abc>>(PARTITIONS_COUNT);
// divide set into 4 different sets for threading purpose
for (int i = 0; i < PARTITIONS_COUNT; i++) {
theSets.add(new HashSet<Abc>());
}
int index = 0;
for (Abc abcObj : abcSet) {
theSets.get(index++ % PARTITIONS_COUNT).add(abcObj);
}
for (final Set<Abc> abcSet1 : theSets) {
e.execute(new Runnable() {
@Override
public void run() {
for (Abc abc : abcSet1) {
//do some modifications with abc and add it to newAbcSet
newAbcSet.add(abc);
}
}
});
}
//Do something with the newAbcSet
【问题讨论】:
标签: java multithreading set threadpool executorservice