【发布时间】:2014-08-27 20:41:03
【问题描述】:
所以我有以下代码,它接受两个数组的输入,并应用一些查询来匹配来自Array1 的元素与来自Array2 的元素,然后它返回两个数组列表中相似的元素数量。
这是我使用的代码:
public static void get_ND_Matches() throws IOException{
@SuppressWarnings("rawtypes")
List<String> array1 = new ArrayList<String>();
List<String> array2 = new ArrayList<String>();
array1 = new ArrayList<String>( ClassesRetrieval.getDBpediaClasses());
array2 = new ArrayList<String>( ClassesRetrieval.fileToArrayListYago());
String maxLabel="";
HashMap<String,Integer> map = new HashMap<String,Integer>();
int number;
HashMap<String,ArrayList<String>> theMap = new HashMap<>();
for(String yagoClass:array2){
theMap.put(yagoClass, getListTwo(yagoClass));
System.out.println("Done for : "+yagoClass );
}
for(String dbClass:array1){
ArrayList<String> result = get_2D_Matches(dbClass);
for(Map.Entry<String, ArrayList<String>> entry : theMap.entrySet()){
String yagoClass=entry.getKey();
Set<String> IntersectionSet =Sets.intersection(Sets.newHashSet(result), Sets.newHashSet(entry.getValue()));
System.out.println(dbClass + " and "+ yagoClass+ " = "+ IntersectionSet.size());
number = IntersectionSet.size();
map.put(yagoClass, number);
}
int maxValue=(Collections.max(map.values()));
for(Entry<String, Integer> entry:map.entrySet()){
if(entry.getValue()==maxValue && maxValue != 0){
maxLabel = entry.getKey();
}
if(maxValue==0){
maxLabel = "Nothing in yago";
}
}
System.out.println("-------------------------------");
System.out.println(dbClass+" from DBPEDIA Corresponds to "+ maxLabel);
System.out.println("-------------------------------");
}
}
此代码返回例如:
来自 DBPEDIA 的演员对应于 Yago_Actor
来自 DBPEDIA 的专辑对应于 Yago_Album
来自 DBPEDIA 的 SomeClass 对应于 Yago 中的任何内容
等等。
在幕后,此代码使用getDBpediaClasses,然后应用Get_2D_Matches(); 方法来获取每个类的结果数组列表。然后将结果的每个 ArrayList 与 getListTwo() 为每个 fileToArrayListYago() 的类生成的另一个 ArrayList 进行比较。
现在,由于所有计算都是在后台进行的(每个数组中有数百万个元素),这个过程需要几个小时才能执行。
我真的很想使用并发/多线程来解决这个问题。谁能告诉我怎么做?
【问题讨论】:
-
Oracle 可以告诉你:docs.oracle.com/javase/tutorial/essential/concurrency :)
-
Java 8 parallel streams 和 lambdas 可以帮助您解决问题。
标签: java multithreading optimization concurrency