我做了一个程序来计算单个文件中的单词, 但是我该如何修改我的程序,以便它给出所有文件中的单词总数(作为一个值)。
我的代码是这样的:
public class WordCount implements Runnable
{
public WordCount(String filename)
{
this.filename = filename;
}
public void run()
{
int count = 0;
try
{
Scanner in = new Scanner(new File(filename));
while (in.hasNext())
{
in.next();
count++;
}
System.out.println(filename + ": " + count);
}
catch (FileNotFoundException e)
{
System.out.println(filename + " blev ikke fundet.");
}
}
private String filename;
}
有一个主类:
public class Main
{
public static void main(String args[])
{
for (String filename : args)
{
Runnable tester = new WordCount(filename);
Thread t = new Thread(tester);
t.start();
}
}
}
以及如何避免竞争条件? 感谢您的帮助。
最佳答案
工作线程:
class WordCount extends Thread
{
int count;
@Override
public void run()
{
count = 0;
/* Count the words... */
...
++count;
...
}
}
还有一个使用它们的类:
class Main
{
public static void main(String args[]) throws InterruptedException
{
WordCount[] counters = new WordCount[args.length];
for (int idx = 0; idx < args.length; ++idx) {
counters[idx] = new WordCount(args[idx]);
counters[idx].start();
}
int total = 0;
for (WordCount counter : counters) {
counter.join();
total += counter.count;
}
System.out.println("Total: " + total);
}
}
许多硬盘不能很好地同时读取多个文件。引用位置对性能有很大影响。
关于java - 多线程 - 计算来自多个文件的总字数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8438497/