gpt4 book ai didi

java - 每次在目录Java中搜索时如何创建新线程

转载 作者:行者123 更新时间:2023-12-03 13:08:01 25 4
gpt4 key购买 nike

我有以下代码:

 public void searchStringInFile(String directory, String word)
{
if (word != null && directory != null)
{

File filePath = new File(directory);
Queue<File> queue = new LinkedList<>();
queue.add(filePath);

while (!queue.isEmpty())
{
File currentFile = queue.poll();
File[] listOfDirectories = currentFile.listFiles();

if (listOfDirectories != null)
{
for (File file : listOfDirectories)
{
if (file.isDirectory())
{
queue.add(file);
}
else
{
Thread thread = new Thread(new Runnable()
{

@Override
public void run()
{
readText(file, word);

}
});
thread.start();
}
}
}
}

}
}


private void readText(File file, String word)
{
Scanner scan = null;
try
{

scan = new Scanner(file);
String line;
int lineNumber = 0;
while (scan.hasNextLine())
{
line = scan.nextLine();
lineNumber++;
if (line.contains(word))
{
System.out.println("Line: " + lineNumber + " contains the word: " + word + " at file: " + file.getAbsolutePath());
}
}

}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
close(scan);
}

它正在目录和子目录中的所有文件中找到 String(word)。我想使其成为多线程应用程序-当它进入目录(或找到目录)时,它必须启动 new Thread并开始在文件中搜索,而我实际上并不知道该怎么做。我使它像上面的代码一样,每次打开文件时都启动 new Thread,但是必须在进入目录时才启动。

最佳答案

如果我正确理解了您的问题,并且希望在循环之后启动线程,则可以这样进行:

 public void searchStringInFile(String directory, String word){
if (word == null || directory == null) {
return;
}

File filePath = new File(directory);
Queue<File> queue = new ConcurrentLinkedQueue<>();
queue.add(filePath);

while (!queue.isEmpty()) {
File currentFile = queue.poll();
File[] listOfDirectories = currentFile.listFiles();

if (listOfDirectories != null)
{
new Thread(() -> {
for (File file : listOfDirectories)
{
if (file.isDirectory()) {
queue.add(file);
} else {
readText(file, word);
}
}
}).start();

}
}
}

您将需要将队列更改为ConcurrentLinkedQueue,这是线程安全的实现,因为现在您有多个线程正在同时更改Queue。

关于java - 每次在目录Java中搜索时如何创建新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52733636/

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