2

私は物乞いをしていて、身を守っています。

私はファイルで見つけたマルチスレッドを整理する必要があります:

find(path)の場所とfind(word)の内容をユーザーが入力します。

  • 最初のスレッドは.txtフォルダー内のファイルを検索し、結果をキューに追加します。
  • キューにファイルがある場合=>2番目のスレッドは、このファイルで何を検索する必要があるかを検索し始めます(単語)。
  • 成功した場合は、このファイルのパス+この単語がファイル内でどのくらいの頻度で出会うかが示されます。

Qestions:

  • 少数のスレッドで動作するキューにArrayListを使用できますか(または代替手段が存在しますか)?
  • キューが空の場合、2番目のスレッドは開始されませんが、最初に必要なファイルが見つかったときに待機します。
  • このタスクに同期を使用し、継承するMultiThreadingSearch(または構成を使用する方がよい)必要がありますか?

コード:

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

class ArrayListOfFiles {
    private Node first, last;

    private class Node {
        String item;
        Node next;
    }

    public boolean isEmpty() {
        return first == null;
    }

    public synchronized void enqueue(String item) {
        Node oldlast = last;
        last = new Node();
        last.item = item;
        last.next = null;
        if (isEmpty())
            first = last;
        else
            oldlast.next = last;
    }

    public synchronized String dequeue() {
        String item = first.item;
        first = first.next;
        if (isEmpty())
            last = null;
        return item;
    }
}

class FolderScan extends MultiThreadingSearch implements Runnable {

    FolderScan(String path, String whatFind) {
        super(path, whatFind);
    }

    @Override
    public void run() {
        findFiles(path);
    }

    ArrayListOfFiles findFiles(String path) {
        File root = new File(path);
        File[] list = root.listFiles();
        for (File titleName : list) {
            if (titleName.isDirectory()) {
                findFiles(titleName.getAbsolutePath());
            } else {
                if (titleName.getName().toLowerCase().endsWith((".txt"))) {
                    textFiles.enqueue(titleName.getName());
                }
            }
        }

        return textFiles;
    }

}

class FileScan extends MultiThreadingSearch implements Runnable {
    Scanner scanner = new Scanner((Readable) textFiles);
    Set<String> words = new HashSet<String>();
    int matches = 0;

    FileScan(String file, String whatFind) {
        super(file, whatFind);
        Thread wordFind = new Thread();
        wordFind.start();
    }

    @Override
    public void run() {
        while (scanner.hasNext()) {
            String word = scanner.next();
            words.add(word);
        }

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

        System.out.println(matches);
    }

}

public class MultiThreadingSearch {
    String path;
    String whatFind;

    ArrayListOfFiles textFiles;

    MultiThreadingSearch(String path, String whatFind) {
        this.path = path;
        this.whatFind = whatFind;
        this.textFiles = new ArrayListOfFiles();

        Thread pathFind = new Thread(new FolderScan(path, whatFind));
//      pathFind.start();

        if (!textFiles.isEmpty()) {
            @SuppressWarnings("unused")
            FileScan fileScan = new FileScan(textFiles.dequeue(), whatFind);
        }

    }

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

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(System.in));
        String path;
        String whatFind;
        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) {
                new MultiThreadingSearch(path, whatFind);
                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();
        }
    }


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

私はException in thread "main" java.lang.StackOverflowErrorこのコードから得ました。
このタスクをどのように解決できますか?

ありがとう、
ナザール。

4

3 に答える 3

5

BlockingQueueをチェックしてください。必要なことを正確に実行します。スレッドは、他のスレッドが新しいアイテムをキューに追加するまでブロックできます。
システムをどのように分解するかについて。私は次のことをします:

  • パス内のtxtファイルを検索するためのクラスを作成します。を実装しRunnableます。あなたはそれに合格pathqueueます。そして、パスでtxtファイルを検索し、それらをキューに追加します。
  • ファイルの内容を検索するためのクラスを作成します。を実装しRunnableます。に渡すwhatFindqueue、キューから新しいファイルが取得され、その内容がチェックされます。

何かのようなもの:

BlockingQueue<File> queue = new LinkedBlockingQueue<File>();
String path = ...;
String whatFind = ...;
FolderScan folderScan = new FolderScan(path, queue);
FileScan fileScan = new FileScan(whatFind, queue);

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

キューに何かが追加さFileScanれるまで待ちたい場合は、 takeメソッドを使用できます。FolderScan

BlockingQueue<File> queue;
File toProcess = queue.take(); // this line blocks current thread (FileScan) until someone adds new item to the queue.
于 2013-02-19T10:58:18.493 に答える
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)) {
            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:24:05.047 に答える
-1

これはあまり建設的に聞こえないかもしれませんが、そのコードを修正するか、最初にこのようなものを読んでからコードを破棄することができます。Stackoverflowは通常、再帰が予想よりも深く実行された結果として発生します。再帰メソッドに再帰を停止する条件があることを確認してください。

于 2013-02-19T10:58:41.660 に答える