您好,我有一个学校项目,我必须用 java 创建一个程序来计算一个或多个文件中的单词数。它应该为每个新文件启动一个新线程。它还应该有锁来保护组合字计数器和 Activity 线程计数器。我尝试过研究锁,但我很难理解这个概念。 这是我到目前为止所能想到的。
public class Main {
public static void main(String[] args)throws InterruptedException {
WordCount[] counters = new WordCount[args.length];
for (int index = 0; index < args.length; ++index)
{
counters[index] = new WordCount(args[index]);
counters[index].start();
}
int total = 0;
for (WordCount counter : counters)
{
counter.join();
total += counter.count;
}
System.out.println("Total:" + total);
}
}
public class WordCount extends Thread {
int count;
@Override
public void run()
{
count = 0; //it will count the words
++count;
}
}
最佳答案
“保护”字计数器实际上只是意味着防止两个线程同时尝试更新字计数器。在 Java 中实现这一点的最简单方法是使用 synchronized
关键字:
class WordCounter {
private int count = 0;
public synchronized void incrementCount() {
count++;
}
}
现在,如果两个线程调用该方法,JVM 将强制一个线程等待另一个线程完成。
接下来您需要一个方法来计算文件中的单词数。那应该是比较简单的。像这样的东西:
private void countWords(Path path) {
for (String line : Files.readAllLines(path)) {
for (String word : line.split("\\s+")) {
counter.incrementCount();
}
}
}
您需要在这里处理 IO 异常。
最后,您需要为每个文件创建一个线程。目前,您正在子类化 Thread
类,但更简单的解决方案是使用您需要运行该线程的 Runnable
创建一个线程:
for (Path path: myFiles) {
Thread thread = new Thread(() -> counter.countWords(path));
thread.run();
}
就是这样。我没有添加代码来保持正在运行的线程计数,但它实际上只是遵循相同的模式。
关于Java字计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53622922/