package union.practice;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* 有两个文本文件,每一行是一个单词,写一个Java程序能够找出这两个文本中相同的单词。
* 1.需要考虑所有有可能出现的异常,需要有较好的用户体验,出现异常应该有友好的提示信息而不是java中的Exception;
* 2.程序尽量简洁高效,要求两个文本中各有10万单词量时,找出相同单词的时间不超过0.5秒; 3.对写的程序要有完整的单元测试代码。
*/
public class App {
// commonStringSet存储最后结果
public static volatile Set<String> commonStringSet = new HashSet<String>();
public static volatile Set<String> setA = new HashSet<String>();
public static volatile Set<String> setB = new HashSet<String>();
/**
* 找出两个文本文件中相同的单词
*
* @param file1
* 文件1文件名
* @param file2
* 文件2文件名
* @param destination
* 相同文本存储的位置
*/
public Set<String> findCommonWordsInTwoFiles(String fileA, String fileB) {
//开启两个线程,分别读取两个文件的内容存储到他们对应的HashSet,同时比较当前读取到的内容是否存在于另一线程对应的集合中,如果在,添加到公共集合
final String tempFileA = fileA;
final String tempFileB = fileB;
Thread tA = new Thread(new Runnable() {
public void run() {
File fA = new File(tempFileA);
try {
BufferedReader bfA = new BufferedReader(new FileReader(fA));
// 读取文件1中的内容存储于set1中
String temp = null;
while ((temp = bfA.readLine()) != null) {
synchronized (setA) {
setA.add(temp);
}
if(setB.contains(temp))
synchronized (commonStringSet) {
commonStringSet.add(temp);
}
}
bfA.close();
} catch (FileNotFoundException e) {
System.out.println("待查找的文件不存在");
} catch (IOException e) {
System.out.println("系统读取文件异常");
}
}
});
tA.start();
Thread tB = new Thread(new Runnable() {
public void run() {
File fB = new File(tempFileB);
try {
BufferedReader bfB = new BufferedReader(new FileReader(fB));
// 读取文件1中的内容存储于set1中
String temp = null;
while ((temp = bfB.readLine()) != null) {
synchronized (setB) {
setB.add(temp);
}
if(setA.contains(temp))
synchronized (commonStringSet) {
commonStringSet.add(temp);
}
}
bfB.close();
} catch (FileNotFoundException e) {
System.out.println("待查找的文件不存在");
} catch (IOException e) {
System.out.println("系统读取文件异常");
}
}
});
tB.start();
//等待AB线程执行结束后返回
try {
tA.join();
tB.join();
} catch (InterruptedException e) {
System.out.println("系统不能处理您的请求");
}
return commonStringSet;
}
}
测试的时候拿已知的HashSet结果与函数返回的结果相比较,但是从运行结果来看,并不总是相等的,我想问题应该是出在同步的层面,求解释(测试时数据量比较大,其中一个文件有10万行,一个文件两百行)