为单线程目录中的所有文件迭代器实用程序功能添加多线程可能性 [英] Adding multi-threading possibility to a single-threaded all-files-in-directory iterator utility function
问题描述
我有一个函数,它可以串行(单线程)遍历文件目录,将所有制表符缩进更改为三空格缩进.
I have a function that serially (single-threaded-ly) iterates through a directory of files, changing all tab indentation to three-space indentation.
我将其用作多线程的第一次尝试. (通过
I'm using it as my first attempt at multi-threading. (Am most of the way through Java Concurrency in Practice...surprised it's eight years old now.)
为了保留其当前的单线程功能,但又增加了多线程的可能性,我正在考虑将功能更改为接受其他单线程执行器.
In order to keep it's current single-threaded functionality, but add in the additional possibility of multi-threading, I'm thinking of changing the function to accept an additional Executor parameter, where the original single-threaded function would now be a call to it, passing in a single threaded executor.
这是解决问题的适当方法吗?
Is this an appropriate way to go about it?
推荐答案
一种方法是@Victor Sorokin在他的答案中建议的:将每个文件的处理包装在Runnable
中,然后提交到Executor
或只需从主线程调用run()
.
One way is as @Victor Sorokin suggests in his answer: wrap the processing of every file in a Runnable
and then either submit to an Executor
or just invoke run()
from the main thread.
另一种可能性是始终在Runnable
中进行相同的包装,然后将其提交给始终提供 Executor
.
Another possibility is to always do the same wrapping in a Runnable
and submit it to an always-given Executor
.
每个文件的处理是否同时执行将取决于给定的Executor
的实现.
Whether processing of each file is executed concurrently or not would depend on the given Executor
's implementation.
对于并行处理,您可以调用传递它的函数,即 ThreadPoolExecutor
作为参数,而对于顺序处理,您可以传入伪造的Executor
,即在调用者线程中运行提交的任务的:
For parallel processing, you could invoke your function passing it i.e. a ThreadPoolExecutor
as an argument, whereas for sequential processing you could pass in a fake Executor
, i.e. one that runs submitted tasks in the caller thread:
public class FakeExecutor implements Executor {
@Override
public void execute(Runnable task) {
task.run();
}
}
我相信这种方式是最灵活的方法.
I believe this way is the most flexible approach.
这篇关于为单线程目录中的所有文件迭代器实用程序功能添加多线程可能性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!