java - 为什么我的 ArrayBlockingQueue 在放入列表后会导致空队列?

标签 java multithreading

这是我第一次在 StackOverflow 上提问。我遇到的问题如下:

我有一个生产者和消费者类。在 Producer 类中,我逐行读取文件并将这些文本行放入字符串列表中。当列表有 x 行时。该列表被添加到 ArrayBlockingQueue。我有一个在主线程中启动的生产者线程。除此之外,我启动了几个消费者线程。消费者线程从队列中取出一个项目,它应该是一个列表,并遍历这个行列表以寻找特定的单词。当找到这个词时,它会增加一个计数变量。

发生的事情是,当消费者从队列中取出一个项目时,它说它是空的。我不明白为什么,因为我的制作人当然应该将它添加到队列中。

我的代码是这样的:

消费类:

public static class Consumer implements Callable<Integer> {

    int count = 0;

    @Override
    public Integer call() throws Exception {
        List<String> list = new ArrayList<>();
        list = arrayBlockingQueueInput.take();
        do {
            if (!list.isEmpty()){
                for (int i = 0; i < arrayBlockingQueueInput.take().size(); i++) {
                    for (String element : list.get(i).split(" ")) {
                        if (element.equalsIgnoreCase(findWord)) {
                            count++;
                        }
                    }
                }
            } else {
                arrayBlockingQueueInput.put(list);
            }
        } while (list.get(0) != "HALT");
        return count;
    }
}

生产者类:

public static class Producer implements Runnable {

    @Override
    public void run() {
        try {
            FileReader file = new FileReader("src/testText.txt");
            BufferedReader br = new BufferedReader(file);

            while ((textLine = br.readLine()) != null) {

                if (textLine.isEmpty()) {
                    continue;
                }

                /* Remove punctuation from the text, except of punctuation that is useful for certain words.
                * Examples of these words are don't or re-enter */
                textLine = textLine.replaceAll("[[\\W]&&[^']&&[^-]]", " ");

                /* Replace all double whitespaces with single whitespaces.
                * We will split the text on these whitespaces later */
                textLine = textLine.replaceAll("\\s\\s+", " ");

                textLine = textLine.replaceAll("\\n", "").replaceAll("\\r", "");

                if (results.isEmpty()) {
                    results.add(textLine);
                    continue;
                }
                if (results.size() <= SIZE) {
                    results.add(textLine);
                    if (results.size() == SIZE) {
                        if (arrayBlockingQueueInput.size() == 14){
                            List<String> list = new ArrayList<String>();
                            list.add(HALT);
                            arrayBlockingQueueInput.put(list);
                        } else{
                            arrayBlockingQueueInput.put(results);
                            results.clear();
                        }
                    }
                }
            }
            /* Count the remaining words in the list
             *  (last lines of the file do perhaps not fill up until the given SIZE, therefore need to be counted here)
             *  Fill the list with empty items if the size of the list does not match with the given SIZE */
            while (results.size() != SIZE) {
                results.add("");
            }
            arrayBlockingQueueInput.put(results);
            List<String> list = new ArrayList<String>();
            list.add(HALT);
            arrayBlockingQueueInput.put(list);
            results.clear();
        } catch (InterruptedException e) {
            producerIsRunning = false;
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

主类:

public void main() throws IOException, InterruptedException {
    System.out.println("Enter the word you want to find: ");
    Scanner scan = new Scanner(System.in);
    findWord = scan.nextLine();

    System.out.println("Starting...");
    long startTime = System.currentTimeMillis();
    Thread producer = new Thread(new Producer());
    producer.start();
    ExecutorService executorService = Executors.newFixedThreadPool(CORE);

    List<Future<Integer>> futureResults = new ArrayList<Future<Integer>>();

    for (int i = 0; i < CORE; i++) {
        futureResults.add(executorService.submit(new Consumer()));
    }

    executorService.shutdown();

    for (Future<Integer> result : futureResults) {
        try {
            wordsInText += result.get();
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    producer.join();

    long stopTime = System.currentTimeMillis();

    System.out.println("The word " + findWord + " appears " + wordsInText + " times in the given text");

    System.out.println("Elapsed time was " + (stopTime - startTime) + " milliseconds.");
}

谁能解释为什么会这样?我想补充一点,我们尝试使用毒丸来通知消费者生产商正在暂停。

回答我们为什么要这样做的问题?对于学校,我们尝试并行处理某个编程问题。我们选择的问题是字符串匹配。我们先做了一个串行解和一个并行解。对于下一个作业,我们必须改进我们的并行解决方案,我们的老师告诉我们这是一种方法。

提前致谢!

尼克

最佳答案

您将列表添加到队列并清除它:

arrayBlockingQueueInput.put(results);
results.clear();

你需要做这样的事情来将列表的副本添加到队列中,这样 clear() 就不会清除队列中的列表:

arrayBlockingQueueInput.put(new ArrayList<String>(results));
results.clear();

关于java - 为什么我的 ArrayBlockingQueue 在放入列表后会导致空队列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50931169/

相关文章:

java - 短信UDP应用

java - 如何正确使用ExecutorService来管理并发运行的SwingWorker数量?

java - GSON JsonElement 转字符串

java - 将数据从 SwingWorker 线程返回或获取/分配给变量。初学者

java - 为 CMake 设置自定义 Java 版本

python - 多线程数据生成器

java - newSingleThreadExecutor 与 new Thread() 与 wait() 和 notify()

android - 长时间运行 Android 'service'

c++ - 在类 vector 中线程化成员函数

c++ - boost 线程死锁,任何人都可以检查为什么?