【发布时间】:2012-07-27 18:03:38
【问题描述】:
我试图弄清楚如何使用 java.util.concurrent 包中的类型来并行处理目录中的所有文件。
我熟悉 Python 中的 multiprocessing 包,使用起来非常简单,所以理想情况下我正在寻找类似的东西:
public interface FictionalFunctor<T>{
void handle(T arg);
}
public class FictionalThreadPool {
public FictionalThreadPool(int threadCount){
...
}
public <T> FictionalThreadPoolMapResult<T> map(FictionalFunctor<T> functor, List<T> args){
// Executes the given functor on each and every arg from args in parallel. Returns, when
// all the parallel branches return.
// FictionalThreadPoolMapResult allows to abort the whole mapping process, at the least.
}
}
dir = getDirectoryToProcess();
pool = new FictionalThreadPool(10); // 10 threads in the pool
pool.map(new FictionalFunctor<File>(){
@Override
public void handle(File file){
// process the file
}
}, dir.listFiles());
我感觉java.util.concurrent 中的类型允许我做类似的事情,但我完全不知道从哪里开始。
有什么想法吗?
谢谢。
编辑 1
按照答案中给出的建议,我写了这样的东西:
public void processAllFiles() throws IOException {
ExecutorService exec = Executors.newFixedThreadPool(6);
BlockingQueue<Runnable> tasks = new LinkedBlockingQueue<Runnable>(5); // Figured we can keep the contents of 6 files simultaneously.
exec.submit(new MyCoordinator(exec, tasks));
for (File file : dir.listFiles(getMyFilter()) {
try {
tasks.add(new MyTask(file));
} catch (IOException exc) {
System.err.println(String.format("Failed to read %s - %s", file.getName(), exc.getMessage()));
}
}
}
public class MyTask implements Runnable {
private final byte[] m_buffer;
private final String m_name;
public MyTask(File file) throws IOException {
m_name = file.getName();
m_buffer = Files.toByteArray(file);
}
@Override
public void run() {
// Process the file contents
}
}
private class MyCoordinator implements Runnable {
private final ExecutorService m_exec;
private final BlockingQueue<Runnable> m_tasks;
public MyCoordinator(ExecutorService exec, BlockingQueue<Runnable> tasks) {
m_exec = exec;
m_tasks = tasks;
}
@Override
public void run() {
while (true) {
Runnable task = m_tasks.remove();
m_exec.submit(task);
}
}
}
我认为代码的工作原理是:
- 文件一个接一个地被读取。
- 文件内容保存在专用的
MyTask实例中。 - 一个容量为 5 的阻塞队列来容纳任务。我依靠服务器一次最多保留 6 个文件的内容的能力 - 5 个在队列中,另一个完全初始化的任务等待进入队列。
- 一个特殊的
MyCoordinator任务从队列中获取文件任务并将它们分派到同一个池中。
好的,所以有一个错误 - 可以创建超过 6 个任务。即使所有池线程都忙,也会提交一些。我打算稍后解决它。
问题是它根本不起作用。 MyCoordinator 线程在第一次删除时阻塞 - 这很好。但它永远不会解除阻塞,即使新任务已放入队列中。谁能告诉我我做错了什么?
【问题讨论】:
标签: java multithreading java.util.concurrent