【发布时间】:2018-10-10 06:08:21
【问题描述】:
我有以下代码:
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,但必须是进入目录的时候。
【问题讨论】:
-
你应该使用执行器而不是启动一个新线程。
-
您使用的
new Thread是在查看文件时。所以你想在每个目录下new Thread,你可以在循环体前面加上。每个循环都会启动一个新线程。 -
我不明白这个问题。您正在创建一个新线程,有什么问题?
标签: java multithreading java-stream