我有一个项目,我必须制作一个WordCounter ..我做到了,它工作正常。

然后,我需要排队,以便获得不同长度的文本并将其添加在一起并打印出来。

我做了一个队列,并试图将其打印出来,在那里它也打印出文本中的单词数目如何,并且可以看到它为队列添加了数字。

但后来我不知道如何从队列中取出这些数字,以便将它们加在一起

这是我的WordCounterTester

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;


public class WordCountTest {

public static void main(String[] args){
    final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
    for(int i = 0; i< args.length; i++){
        Runnable r = new WordCount(args[i],queue);
        Thread t = new Thread(r);
        t.start();
    }

}

}


还有我的WordCounter

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;

class WordCount implements Runnable {

public int result;
private String s;
Thread runner;
private BlockingQueue<String> queue;

public WordCount(String s, BlockingQueue<String> queue){
    this.s = s;
    this.queue = queue;
}

public void run() {
    try{
        FileReader fr = new FileReader(s);
        Scanner scanner = new Scanner(fr);
        for(int i = 0; true; i++){
            result = i;
            scanner.next();
        }
    }catch(FileNotFoundException e){
        System.out.println("Du har skrevet en fil der ikke findes, den fil vil blive skrevet ud med 0 ord");
    }
    catch(NoSuchElementException e){}
    System.out.println(s + ": " + result);
    Integer.toString(result);
    queue.add(result + "");
    System.out.println(queue);
}

}


当我用6个不同的.txt运行程序时,我得到的是什么,顺序可能会有所不同,因为它是多线程的,所以顺序不同是首先完成的:)

5.txt: 1
[1]
6.txt: 90
[1, 90]
4.txt: 576
[1, 90, 576]
3.txt: 7462
[1, 90, 576, 7462]
1.txt: 7085
[1, 90, 576, 7462, 7085]
2.txt: 11489
[1, 90, 576, 7462, 7085, 11489]


有谁知道我该如何做?

最佳答案

我认为您所缺少的是main需要与每个已将每个文件计数添加到队列中之后产生的线程一起加入。

public static void main(String[] args){
    final BlockingQueue<Integer> queue = new LinkedBlockingQueue<String>();
    Thread[] threads = new Thread[args.length];
    for (int i = 0; i< args.length; i++){
        Runnable r = new WordCount(args[i], queue);
        threads[i] = new Thread(r);
        threads[i].start();
    }

    // wait for the threads to finish
    for (Thread t : threads) {
        t.join();
    }

    int total = 0;
    for (Integer value : queue) {
        total += value;
    }
    System.out.println(total);
}


在这里的代码中,我实现了@Ben van Gompel的建议,在队列中添加Integer而不是String

您还可以使用AtomicInteger类,并执行以下操作:

final AtomicInteger total = new AtomicInteger(0);
...
    Runnable r = new WordCount(args[i], total);
...
// join loop
// no need to total it up since each thread would be adding to the total directly
System.out.println(total);


在WordCount代码内部,您可以使用AtomicInteger

System.out.println(s + ": " + result);
// add the per-file count to the total
total.incrementAndGet(result);
// end

10-07 19:28
查看更多