我已經創建了一個類來計算同一目錄中給定文件中的單詞。鑑於文件非常大,我決定使用多線程實現多個文件的計數。LinkedBlockingQueue只返回多個線程之一
當按照以下指定的方式運行DriverClass時,它會卡在第一個線程中。 我在做什麼錯?在我遍歷queue.take()時,人們會期望解析器等待某些東西來檢索並繼續前進。在線程1中卡住會讓我懷疑將()放入隊列時出錯。
謝謝,提前!
DriverClass:
public class WordCountTest {
public static void main(String[] args){
if (args.length<1){
System.out.println("Please specify, atleast, one file");
}
BlockingQueue<Integer> threadQueue = new LinkedBlockingQueue<>();
Runnable r;
Thread t;
for (int i = 0; i<args.length; i++){
r = new WordCount(args[i], threadQueue);
t = new Thread(r);
t.start();
int total = 0;
for (int k = 0; k<args.length; k++){
try {
total += threadQueue.take();
} catch (InterruptedException e){
}
}
System.out.println("Total wordcount: " + total);
}
}
}
WordCountClass:
public class WordCount implements Runnable {
private int myId = 0;
private String _file;
private BlockingQueue<Integer> _queue;
private static int id = 0;
public WordCount(String file, BlockingQueue<Integer> queue){
_queue = queue;
_file = file;
myId = ++id;
}
@Override
public void run() {
System.out.println("Thread " + myId + " running");
try {
_queue.put(countWord(_file));
} catch (InterruptedException e){
}
}
public int countWord(String file){
int count = 0;
try {
Scanner in = new Scanner(new FileReader(file));
while (in.hasNext()){
count++;
in.next();
}
} catch (IOException e){
System.out.println("File," + file + ",not found");
}
return count;
}
}
是的,我來到相同的解決方案,並已實施它,在這個答案之前。無論如何謝謝你! - 我已將您的答案標記爲最終答案。感謝您的時間! –