gpt4 book ai didi

java - 如何组织多线程与队列一起工作?

转载 作者:行者123 更新时间:2023-11-30 07:18:58 25 4
gpt4 key购买 nike

我是初学者,让自己保持警惕。

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

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

  • 第一个线程在文件夹中找到.txt文件并将结果添加到队列中;
  • 当队列有文件时 => 第二个线程开始在这个文件中查找需要找到什么(单词)。
  • 如果找到成功将显示这条路径文件 + 这个词在文件中出现的频率。

问题:

  • 我们可以将 ArrayList(或存在任何替代方案)用于只使用少数线程的队列吗?
  • 如果队列为空,第二个线程不启动,而是在第一个找到需要的文件时等待怎么办?
  • 我们是否需要为此任务使用同步并继承 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
如何解决这个任务?

谢谢,
纳扎尔。

最佳答案

检查 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 等到 FolderScan 向队列添加内容,您可以使用 take方法:

BlockingQueue<File> queue;
File toProcess = queue.take(); // this line blocks current thread (FileScan) until someone adds new item to the queue.

关于java - 如何组织多线程与队列一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14955657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com