gpt4 book ai didi

java - 多线程遍历和枚举目录

转载 作者:行者123 更新时间:2023-12-02 15:58:21 27 4
gpt4 key购买 nike

我正在运行一个线程来遍历我的本地目录(无子目录),一旦获得文本文件,我就会启动一个新线程来搜索该文件中的单词。

下面的代码有什么问题吗?

搜索和遍历分别工作得很好。但是当我把它放在一起时,出现了一些问题,它跳过了一些文件(不完全是,由于多线程对象同步没有正确发生)。

请帮帮我。

遍历.java

    public void executeTraversing() {
Path dir = null;
if(dirPath.startsWith("file://")) {
dir = Paths.get(URI.create(dirPath));
} else {
dir = Paths.get(dirPath);
}
listFiles(dir);
}

private synchronized void listFiles(Path dir) {
ExecutorService executor = Executors.newFixedThreadPool(1);
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path file : stream) {
if (Files.isDirectory(file)) {
listFiles(file);
} else {
search.setFileNameToSearch(file);
executor.submit(search);
}
}
} catch (IOException | DirectoryIteratorException x) {
// IOException can never be thrown by the iteration.
// In this snippet, it can only be thrown by
// newDirectoryStream.
System.err.println(x);
}
}

Search.java

    /**
* @param wordToSearch
*/
public Search(String wordToSearch) {
super();
this.wordToSearch = wordToSearch;
}

public void run() {
this.search();
}

private synchronized void search() {
counter = 0;

Charset charset = Charset.defaultCharset();
try (BufferedReader reader = Files.newBufferedReader(fileNameToSearch.toAbsolutePath(), charset)) {
// do you have permission to read this directory?
if (Files.isReadable(fileNameToSearch)) {
String line = null;
while ((line = reader.readLine()) != null) {
counter++;
//System.out.println(wordToSearch +" "+ fileNameToSearch);

if (line.contains(wordToSearch)) {
System.out.println("Word '" + wordToSearch
+ "' found at "
+ counter
+ " in "
+ fileNameToSearch);
}
}
} else {
System.out.println(fileNameToSearch
+ " is not readable.");
}

} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}

}

最佳答案

您在此处继续重复使用的此搜索实例:

search.setFileNameToSearch(file);
executor.submit(search);

虽然它的实际 search() 方法是同步的,但看起来当它实际开始搜索某些内容时 setFileNameToSearch() 会被调用多次,这可以解释跳过的原因。

每次创建一个新的Search实例,那么您就不需要同步实际的search()函数。

关于java - 多线程遍历和枚举目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17819626/

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