Пишу программу которая считает количество повторений каждого слова в текстовом фаиле. В качестве теста взял текстовый фаил в котором, 12 раз повторяется слово "Привет".
class WordCountWithThread {
private static int i =0;
private static Map<String, Integer> mainMap = new ConcurrentHashMap<String, Integer>();
public static void main(String[] args) throws Exception {
long startTime = System.currentTimeMillis();
String PathToFile = "D:\\text1.txt";
ArrayList<String> wordsTemp = new ArrayList<String>();
try {
File file = new File(PathToFile);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
i++;
if (wordsTemp.size()<500000) {
String FinalWord = convertedWord(scanner.next().toLowerCase());
wordsTemp.add(FinalWord);
}
else if (wordsTemp.size()==500000){
Runnable r = new NewThread(wordsTemp,mainMap);
new Thread(r).start();
wordsTemp = new ArrayList<String>();
wordsTemp.add(convertedWord(scanner.next().toLowerCase()));
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (wordsTemp.size()>0){
Runnable r = new NewThread(wordsTemp,mainMap);
new Thread(r).start();
}
showResult(startTime);
}
// Создание второго потока
private static class NewThread implements Runnable {
Thread thread;
ArrayList <String> strings;
Map<String, Integer> map;
// Конструктор
NewThread(ArrayList <String> strings,Map<String, Integer> map) {
this.strings = strings;
this.map = map;
thread = new Thread(this, "Поток для примера");
thread.start();
}
public void run() {
wordCount(strings, map);
}
}
private static void wordCount(ArrayList<String> strings, Map<String, Integer> map) {
String s;
for (String string : strings) {
s = string;
if (string != null) {
if (!map.containsKey(s)) {
map.put(s, 1);
} else {
map.compute(s, (tokenKey, oldValue) -> oldValue == null ? 1 : oldValue + 1);
}
}
};
mainMap = map;
}
private static void showResult(long startTime){
for (Map.Entry<String, Integer> e : mainMap.entrySet()) {
System.out.println(e.getKey() + ":"
+ e.getValue());
}
System.out.println("Уникальных слов: "+mainMap.size());
System.out.println("Всего слов: "+i);
long timeSpent = System.currentTimeMillis() - startTime;
System.out.println("программа выполнялась " + timeSpent + " миллисекунд");
}
//Преобразование
static String convertedWord(String word){
return word.replaceAll("\\p{Punct}", "");
}
В итоге выводит, что "Уникальных слов: 2". В чём может быть ошибка?
EDIT переписано на fork/join class WordCountWithThread {
private static int i =0;
public static void main(String[] args) throws Exception {
Map<String, Integer> mainMap = new ConcurrentHashMap<String, Integer>();
long startTime = System.currentTimeMillis();
String PathToFile = "D:\\text1.txt";
ArrayList<String> wordsTemp = new ArrayList<String>();
try {
File file = new File(PathToFile);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
i++;
if (wordsTemp.size()<500000) {
String FinalWord = convertedWord(scanner.next().toLowerCase());
wordsTemp.add(FinalWord);
}
else if (wordsTemp.size()==500000){
WordCounter wordCounter = new WordCounter(wordsTemp,mainMap);
ForkJoinPool pool = new ForkJoinPool();
pool.execute(wordCounter);
wordsTemp = new ArrayList<String>();
wordsTemp.add(convertedWord(scanner.next().toLowerCase()));
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (wordsTemp.size()>0) {
WordCounter wordCounter = new WordCounter(wordsTemp,mainMap);
ForkJoinPool pool = new ForkJoinPool();
pool.execute(wordCounter);
wordCounter.join();
}
showResult(startTime,mainMap);
}
private static void showResult(long startTime, Map<String, Integer> mainMap){
for (Map.Entry<String, Integer> e : mainMap.entrySet()) {
System.out.println(e.getKey() + ":"
+ e.getValue());
}
System.out.println("Уникальных слов: "+mainMap.size());
System.out.println("Всего слов: "+i);
long timeSpent = System.currentTimeMillis() - startTime;
System.out.println("программа выполнялась " + timeSpent + " миллисекунд");
}
//Преобразование
static String convertedWord(String word){
return word.replaceAll("\\p{Punct}", "");
}
}
class WordCounter extends RecursiveTask<Map<String, Integer>> {
ArrayList <String> strings;
Map<String, Integer> map;
WordCounter(ArrayList<String> strings, Map<String, Integer> map) {
this.strings = strings;
this.map = map;
}
@Override
protected Map<String, Integer> compute() {
String s;
for (String string : strings) {
s = string;
if (string != null) {
map.compute(s, (tokenKey, oldValue) -> oldValue == null ? 1 : oldValue + 1);
}
}
return map;
}
После изменения выводит: привет:1 привет:11 Уникальных слов: 2 Всего слов: 12 Стал правильно складывать map, но всё равно работает не правильно.