1

我需要在文件中组织多线程查找:

用户输入 where find(path) 和 what find(word);

第一个线程在文件夹中找到 .txt 文件并将结果添加到队列中;当队列有一些文件=>第二个线程开始在这个文件中查找需要查找的内容(单词)。如果找到成功,将显示此文件的路径 + 该单词在文件中相遇的次数。
但是我有NoSuchElementException.

输出:

   Exception in thread "pool-1-thread-2" java.util.NoSuchElementException  
    at java.util.AbstractQueue.remove(AbstractQueue.java:117)  
    at task.FileScan.run(FileScan.java:77)  
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)  
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)  
    at java.lang.Thread.run(Thread.java:722).  

代码:

import java.util.concurrent.*;
import java.util.*;
import java.io.*;

class FolderScan implements Runnable {

    private String path;
    private BlockingQueue<File> queue;
    private CountDownLatch latch;
    private File endOfWorkFile;

    FolderScan(String path, BlockingQueue<File> queue, CountDownLatch latch,
            File endOfWorkFile) {
        this.path = path;
        this.queue = queue;
        this.latch = latch;
        this.endOfWorkFile = endOfWorkFile;
    }

    public FolderScan() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public void run() {
        findFiles(path);
        queue.add(endOfWorkFile);
        latch.countDown();
    }

    private void findFiles(String path) {

        File root = new File(path);
        File[] list = root.listFiles();
        for (File currentFile : list) {
            if (currentFile.isDirectory()) {
                findFiles(currentFile.getAbsolutePath());
            } else {
                if (currentFile.getName().toLowerCase().endsWith((".txt"))) {
                    queue.add(currentFile);
                }
            }
        }

    }

}

public class FileScan implements Runnable {

    private String whatFind;
    private BlockingQueue<File> queue;
    private CountDownLatch latch;
    private File endOfWorkFile;

    public FileScan(String whatFind, BlockingQueue<File> queue,
            CountDownLatch latch, File endOfWorkFile) {
        this.whatFind = whatFind;
        this.queue = queue;
        this.latch = latch;
        this.endOfWorkFile = endOfWorkFile;
    }

    public FileScan() {
        // TODO Auto-generated constructor stub
    }

    Set<String> words = new HashSet<String>();
    int matches = 0;

    @Override
    public void run() {

        while (true) {
            File file = queue.remove();
            if (file == endOfWorkFile) {
                break;
            }
            scan(file);
        }

        latch.countDown();
    }

    private void scan(File file) {
        Scanner scanner = null;
        try {
            scanner = new Scanner(file);
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException.");
            e.printStackTrace();
        }
        while (scanner.hasNext()) {
            String word = scanner.next();
            words.add(word);
        }

        if (words.contains(this.whatFind)) {
            // System.out.println("File:" + ((File) words).getAbsolutePath());
            matches++;
        }
        @SuppressWarnings("unused")
        String myStr = String.format("File: %s and the number of matches "
                + "is = %d", file.getAbsolutePath(), matches);
        System.out.println("myStr");

        matches = 0;
    }

    // ask user about input
    public void askUserPathAndWord() {

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(System.in));
        String path;
        String whatFind;
        BlockingQueue<File> queue = new LinkedBlockingQueue<File>();

        try {
            System.out.println("Please, enter a Path and Word"
                    + "(which you want to find):");
            System.out.println("Please enter a Path:");
            path = bufferedReader.readLine();
            System.out.println("Please enter a Word:");
            whatFind = bufferedReader.readLine();

            if (path != null && whatFind != null) {

                File endOfWorkFile = new File("GameOver.tmp");
                CountDownLatch latch = new CountDownLatch(2);

                FolderScan folderScan = new FolderScan(path, queue, latch,
                        endOfWorkFile);
                FileScan fileScan = new FileScan(whatFind, queue, latch,
                        endOfWorkFile);

                Executor executor = Executors.newCachedThreadPool();
                executor.execute(folderScan);
                executor.execute(fileScan);

                latch.await();
                System.out.println("Thank you!");
            } else {
                System.out.println("You did not enter anything");
            }

        } catch (IOException | RuntimeException e) {
            System.out.println("Wrong input!");
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
            e.printStackTrace();
        }
    }

    /**
     * @param args
     */

    public static void main(String[] args) {
        new FileScan().askUserPathAndWord();
    }
}

怎么能解决这个问题?

谢谢,
纳扎尔。

4

2 回答 2

5

你检查过javadoc吗?

有一个很好的表格,根据您的需要显示要调用的方法。在您的情况下,我猜您需要阻止并等待队列为空。如果是这种情况,您应该替换removetake.

注意:我没有检查您的代码的详细信息,因此可能存在其他问题。

于 2013-02-22T21:07:47.700 回答
0
package task;

import java.util.concurrent.*;
import java.util.*;
import java.io.*;

class FolderScan implements Runnable {

    private String path;
    private BlockingQueue<File> queue;
    private CountDownLatch latch;
    private File endOfWorkFile;

    FolderScan(String path, BlockingQueue<File> queue, CountDownLatch latch,
            File endOfWorkFile) {
        this.path = path;
        this.queue = queue;
        this.latch = latch;
        this.endOfWorkFile = endOfWorkFile;
    }

    public FolderScan() {  }

    @Override
    public void run() {
        findFiles(path);
        queue.add(endOfWorkFile);
        latch.countDown();
    }

    private void findFiles(String path) {

        try {
            File root = new File(path);
            File[] list = root.listFiles();
            for (File currentFile : list) {
                if (currentFile.isDirectory()) {
                    findFiles(currentFile.getAbsolutePath());
                } else {
                    if (currentFile.getName().toLowerCase().endsWith((".txt"))) {
                            queue.put(currentFile);
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

}

public class FileScan implements Runnable {

    private String whatFind;
    private BlockingQueue<File> queue;
    private CountDownLatch latch;
    private File endOfWorkFile;

    public FileScan(String whatFind, BlockingQueue<File> queue,
            CountDownLatch latch, File endOfWorkFile) {
        this.whatFind = whatFind;
        this.queue = queue;
        this.latch = latch;
        this.endOfWorkFile = endOfWorkFile;
    }

    public FileScan() {     }

    Set<String> words = new HashSet<String>();
    int matches = 0;

    @Override
    public void run() {

        while (true) {
            try {
                File file;
                file = queue.take();

                if (file == endOfWorkFile) {
                    break;
                }

                scan(file);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        latch.countDown();
    }

    private void scan(File file) {
        Scanner scanner = null;
        try {
            scanner = new Scanner(file);
        } catch (FileNotFoundException e) {
            System.out.println("FileNotFoundException.");
            e.printStackTrace();
        }
        while (scanner.hasNext()) {
            String word = scanner.next();
            words.add(word);
        }

        if (words.contains(this.whatFind)) {
            // System.out.println("File:" + ((File) words).getAbsolutePath());
            matches++;
        }

        String myStr = String.format("File: %s and the number of matches "
                + "is = %d", file.getAbsolutePath(), matches);
        System.out.println(myStr);

        matches = 0;
    }

    // ask user about input
    public void askUserPathAndWord() {

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(System.in));
        String path;
        String whatFind;
        BlockingQueue<File> queue = new LinkedBlockingQueue<File>();

        try {
            System.out.println("Please, enter a Path and Word"
                    + "(which you want to find):");
            System.out.println("Please enter a Path:");
            path = bufferedReader.readLine();
            System.out.println("Please enter a Word:");
            whatFind = bufferedReader.readLine();

            if (path != null && whatFind != null) {

                File endOfWorkFile = new File("GameOver.tmp");
                CountDownLatch latch = new CountDownLatch(2);

                FolderScan folderScan = new FolderScan(path, queue, latch,
                        endOfWorkFile);
                FileScan fileScan = new FileScan(whatFind, queue, latch,
                        endOfWorkFile);

                Executor executor = Executors.newCachedThreadPool();
                executor.execute(folderScan);
                executor.execute(fileScan);

                latch.await();
                System.out.println("Thank you!");
            } else {
                System.out.println("You did not enter anything");
            }

        } catch (IOException | RuntimeException e) {
            System.out.println("Wrong input!");
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
            e.printStackTrace();
        }
    }

    /**
     * @param args
     */

    public static void main(String[] args) {
        new FileScan().askUserPathAndWord();
    }
}
于 2013-02-22T21:15:13.717 回答