【发布时间】:2017-10-17 08:11:02
【问题描述】:
我正在尝试分别计算三个文本文件中的单词数。三个类在多线程中运行。在每个线程中,计数单词的总和将传递给类计数器,并在所有线程完成后更新以将所有计数加到计数器。
我遇到了两个问题,“totalWordCount”可以由类设置器更新。但它不能由同一类的吸气剂得到。另一个问题是我无法检查 Readfiles 线程是否活着。
我在网上搜索过很多次都不能解决,欢迎大家提出意见,非常感谢!
NumberWords 类: 公共课 NumberWords { 私有 int 活动线程; 私人 int 总字数; 私有字符串 getThreadName;
public NumberWords(int activeThread) {
this.activeThread = activeThread;
}
public synchronized void incTotalWordCount(int n) {
totalWordCount += n;
System.out.println("The total word count is " + totalWordCount);
}
public synchronized void printCount() {
System.out.println("The total word count(print count) is " + totalWordCount);
}
public synchronized void decActiveThread() {
getThreadName = Thread.currentThread().getName();
System.out.println(getThreadName);
if (Thread.getAllStackTraces().keySet().size() != 0) {
// Get number of active threads
activeThread = Thread.getAllStackTraces().keySet().size();
activeThread--;
if (activeThread == 0) {
System.out.println("The total number of word in the three files is " + totalWordCount);
System.out.println("The active threads is/are " + activeThread);
}
}
}
}
读取文件并统计字数:
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
public class ReadFile1 extends Thread implements Runnable {
private NumberWords nw;
public ReadFile1(NumberWords nw) {
this.nw = nw;
}
//set file path
String path1 = System.getProperty("user.dir") + File.separator + "text1.txt";
BufferedReader br1 = null;
public void run() {
try {
br1 = new BufferedReader(new FileReader(path1));
String contentLine = br1.readLine();
while (contentLine != null) {
// Count number of words
String[] parts = contentLine.split(" ");
int count = 0;
for (int i = 0; i < parts.length; i++) {
count++;
}
// Check number of words counted.
System.out.println("The number of words in file(text1.txt) is " + count);
//Pass words count to sum
nw.incTotalWordCount(count);
contentLine = br1.readLine();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (br1 != null) {
br1.close();
}
} catch (IOException ioe) {
System.out.println("Error in closing the BufferedReader");
}
}
}
}
主类:
public class TestReadFile {
public static void main(String args[]){
NumberWords nw = new NumberWords(args.length);
Thread rf1 = new Thread(new ReadFile1(nw));
Thread rf2 = new Thread(new ReadFile2(nw));
Thread rf3 = new Thread(new ReadFile3(nw));
rf1.start();
rf2.start();
rf3.start();
//Get total word cont
nw.decActiveThread();
}
}
【问题讨论】:
-
这些类的格式不是很好。 IDE 可以处理这个问题。不幸的是,它们也不编译。此外,还缺少两个类:
ReadFile2和ReadFile3。我还不清楚你在问什么。 -
感谢回复,ReadFile2 & 3 与 ReadFile1 唯一的不同就是读取不同的文本文件,除了这一点都是相同的代码。
标签: java multithreading methods