Java 将来自不同线程的值添加到全局集中,并等待所有线程完成
我是线程新手,我想知道是否可以使用线程将大量数据分割成小任务,从而减少处理时间 我已将该集合拆分为多个集合列表,来自executor service的每个线程都会占用该集合并将该集合添加到另一个集合(全局声明)abcSet。 我需要每个线程将对象添加到此集中,在所有线程完成添加后,继续使用abcSet完成剩余的工作 下面是示例代码。请帮帮我Java 将来自不同线程的值添加到全局集中,并等待所有线程完成,java,multithreading,set,threadpool,executorservice,Java,Multithreading,Set,Threadpool,Executorservice,我是线程新手,我想知道是否可以使用线程将大量数据分割成小任务,从而减少处理时间 我已将该集合拆分为多个集合列表,来自executor service的每个线程都会占用该集合并将该集合添加到另一个集合(全局声明)abcSet。 我需要每个线程将对象添加到此集中,在所有线程完成添加后,继续使用abcSet完成剩余的工作 下面是示例代码。请帮帮我 private static final int PARTITIONS_COUNT = 4; final Set<Abc> newAbcSet
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
private static final int PARTITIONS\u COUNT=4;
最终集newAbcSet=newhashset();
最终设置abcSet=//来自数据库的数据
ExecutorService e=Executors.newFixedThreadPool(4);
List theset=newarraylist(分区计数);
//为便于穿线,将组件分为4个不同的组件
对于(int i=0;i
在之后添加while(!e.isTerminated()){}
以停止执行:
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);
}
}
});
}
while (!e.isTerminated()){}
for(最终设置abcSet1:theSets){
e、 执行(新的Runnable(){
@凌驾
公开募捐{
对于(Abc:abcSet1){
//对abc进行一些修改,并将其添加到newAbcSet
新增abcset.add(abc);
}
}
});
}
而(!e.isTerminated()){}
- 要防止种族限制,您应该使用,例如:
final Set<Abc> newAbcSet= Collections.synchronizedSet(new HashSet<Abc>());
如果仍然需要线程池,请参阅此
e.shutDown(); // previously submitted tasks are not affected
e.awaitTermination(); // Blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.
//Do something with the newAbcSet