簡體   English   中英

為什么我的ArrayBlockingQueue在列入列表后導致空隊列?

[英]Why does my ArrayBlockingQueue result in an empty queue after putting a list in it?

這是我第一次在StackOverflow上提出問題。 我遇到的問題如下:

我有一個制作人和消費者類。 在Producer類中,我逐行讀取文件,並將這些文本行放在字符串列表中。 當列表具有x行數時。 此列表將添加到ArrayBlockingQueue。 我有一個在主線程中啟動的生產者線程。 除此之外,我開始使用幾個Consumer線程。 Consumer線程從隊列中獲取一個項目,該項目應該是一個列表,並遍歷此行列表以查找特定單詞。 當找到該單詞時,它會遞增計數變量。

發生的事情是當Consumer從隊列中獲取一個項目時,它表示它是空的。 我無法弄清楚為什么,因為我的制作人當然應該將它添加到隊列中。

我的代碼看起來像這樣:

消費者階層:

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.");
}

任何人都可以解釋為什么會這樣嗎? 我想補充一點,我們嘗試使用毒丸來通知消費者生產者是在HALT上。

要回答這個問題我們為什么要這樣做呢? 對於學校,我們嘗試並行化某個編程問題。 我們選擇的問題是字符串匹配。 我們首先制作了串行解決方案和並行解決方案。 對於下一個任務,我們必須改進我們的並行解決方案,我們的老師告訴我們這是一種方法。

提前致謝!

缺口

您將列表添加到隊列並清除它:

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

您需要執行以下操作以將列表副本添加到隊列中,以便clear()不會清除隊列中的列表:

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

在老師的幫助下,他幫我們找到了問題。 有兩個錯誤。 一個是生產者類。 我有代碼在主while循環中發出生產者的HALT信號。 這不應該做。

除此之外,我在Do-While之前在Consumer類中執行的.take()應該在do-while循環中完成。

正確的代碼如下所示:

消費者階層:

public static class Consumer implements Callable<Integer> {

    int count = 0;

    @Override
    public Integer call() throws Exception {
        List<String> list = new ArrayList<>();
        do {
            list = arrayBlockingQueueInput.take();
            if (!list.get(0).equals(HALT)){
                for (int i = 0; i < list.size(); i++) {
                    for (String element : list.get(i).split(" ")) {
                        if (element.equalsIgnoreCase(findWord)) {
                            count++;
                        }
                    }
                }
            } else {
                arrayBlockingQueueInput.put(list);
            }
        } while (!list.get(0).equals(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) {
                        arrayBlockingQueueInput.put(new ArrayList<String>(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(new ArrayList<String>(results));
            List<String> list = new ArrayList<String>();
            list.add(HALT);
            arrayBlockingQueueInput.put(list);
            results.clear();
        } catch (InterruptedException e) {
            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.");
}

感謝@Ivan幫助我使用.clear方法調用結果。 沒有這個,代碼解決方案就不起作用了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM