我正在练习一点并发。
public class WordOccurrencesBigFile {
private String words;
private ConcurrentHashMap<String, Pair<String, Integer>> wordOccurrencesMap = new ConcurrentHashMap<>();
public WordOccurrencesBigFile(String wordsLine) {
this.words = wordsLine;
}
public void processWords() {
parseWordsLines();
printOrderAlphabetically();
printOrderByCount();
printByInsertionOrder();
}
private void parseWordsLines() {
String[] wordsLinesArray = words.split("\n");
ExecutorService executor = Executors.newFixedThreadPool(5);
for(String wordsLine: wordsLinesArray) {
executor.execute(() -> parseWords(wordsLine));
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
private void parseWords(String wordsLine) {
System.out.println(Thread.currentThread().getName() + " Start.");
System.out.println(Thread.currentThread().getName() + " Processing line: '" + wordsLine + "'");
String[] wordsArray = wordsLine.split(" ");
}
}
在 parseWordsLines 上,使用 5 个线程池创建了一个 ExecutorService,并且 WordOccurrencesBigFile 类使用由“\n”创建的多行字符串实例化。目的是让每一行由不同的线程处理,并在 Map 上插入唯一单词的计数。
我期望通过使用 ConcurrentHashMap 足以处理我有多个线程读取和写入地图的事实。但是在我执行课程的大部分时间里,我得到了不同的计数。(奇怪的是主要是针对“bb”这个词。
但是添加了 synchronized(this) 问题就解决了。
有人可以解释为什么这种行为,解决这个问题的最佳方法,我应该将“this”传递给同步块或线程正在访问的对象吗?
慕后森
蓝山帝景
相关分类