一旦现有线程是免费的java,就将任务分配给它们



我有一大组单词,需要对每个单词执行一项任务。为了提高速度,我想使它成为多线程的。目前,我只是使用foreach循环来遍历列表中的每个项目。我想做的是让8个线程检查我给它们的单词,然后将结果写入文件。

目前,这是我正在使用的代码:

public static void main(String[] args) {
System.setProperty("http.agent", "Chrome");
readWords();
Collections.shuffle(words);
words.forEach(word -> {
if (CheckValidity.checkValidity(word)) {
System.out.println(word);
try(PrintWriter writer = new PrintWriter(new FileWriter("output.txt",true)))
{
writer.printf("%srn", word);
} catch (IOException e) {
e.printStackTrace();
}
}
});
System.out.println("Done!");
}

我将如何在多线程中实现这一点?我找不到任何对我有意义的信息,我可以在任何空闲线程中向方法输入值。很抱歉,如果这不是多线程的工作方式,我以前从未用一个以上的线程写过任何东西,所以我不知道什么是可能的,什么是不可能的。

将对CheckValidity的调用并行化的最快方法是使用并行流。类似的东西

public static void main(String[] args) {
List<String> words = readWords();
Collections.shuffle(words);
words.stream()
.unordered()
.parallel()
.filter(CheckValidity::checkValidity)
.forEach(word -> {
System.out.println(word);
try(PrintWriter writer = new PrintWriter(new FileWriter("output.txt",true)))
{
writer.printf("%srn", word);
} catch (IOException e) {
e.printStackTrace();
}

});
System.out.println("Done!");
}

但是,如果您的应用程序还并行地执行其他事情,则这不应该是您的生产解决方案,因为这在内部使用公共ForkJoinPool,并且用非CPU绑定操作阻止它可能会减慢应用程序的其他部分(例如其他并行流(的速度。

对于更健壮的解决方案,您应该看看ThreadPoolExecutitor,它允许创建具有定义大小、超时等的单独线程池。

最新更新