【发布时间】:2020-04-17 17:50:11
【问题描述】:
我制作了一个程序来计算文件中目标字符串的出现次数。它应该使用并行性来完成此任务,但我似乎无法弄清楚如何编写 run() 来仅评估文件的一部分,以便它的不同线程可以评估文件的其余部分。至少,这是我对并行的理解。我已经在文档中观看了几天的视频,真的只需要有人向我解释一下;不是如何逐步解决我的特定问题本身,而是解释多线程,而不是使用带有打印线程 id 的循环的主方法。我知道我的类需要实现 Runnable 并且 run() 需要被覆盖。我不确定应该如何编写 run() 以仅在无法传递参数时处理文件的一部分。
public static void main(String[] args) {
new Thread(new Test()).start();
new Thread(new Test()).start();
System.out.println("My program counts: " + Test.getTotal() + " occurences of 'the'.");
}
}
public class Test implements Runnable {
private File alice = new File(getCurrentDir() + "/alice.txt");
private String[] words;
private BufferedReader reader;
private StringBuilder sb;
private int count;
private static int total;
public void run() {
getAlice();
for(int i = 0; i < words.length; i++) {
if(words[i].toLowerCase().equals("the")) {
count++;
}
}
total = count;
}
public void getAlice() {
try{
reader = new BufferedReader(new FileReader(alice));
sb = new StringBuilder();
String line = "";
while((line = reader.readLine()) != null) {
sb.append(line);
}
words = sb.toString().split(" ");
} catch (IOException e) {
e.printStackTrace();
}
}
public String getCurrentDir() {
String currDir = System.getProperty("user.dir");
return currDir;
}
public String[] getWords() {
return words;
}
static int getTotal() {
return total;
}
}```
【问题讨论】:
-
Files.lines(Path.of(System.getProperty("user.dir"), "alice.txt")).parallel().mapToInt(l -> l.split(" ").count).sum();
标签: java multithreading