我有一堆要通过线程池执行的可运行文件。但是,每个可运行文件也会将一些结果写入某个文件。所以现在,runnable 的接口很简单:
class MyRunnable implements Runnable {
...
MyRunnable(BufferedWriter writer, Task t) {
this.writer = writer;
this.task = t;
}
public void run() {
...
this.writer.write(SOME_DATA);
}
}
但是,我想要将一个 BufferedWriter(换句话说,一个输出文件)与 Executor 池中的每个线程相关联。但是,我使用如下方式调用该.execute
函数:ExecutorService
BufferedWriter[] writers = initialize to 20 BufferedWriters;
ExecutorService executor = Executors.newFixedThreadPool(20);
for (Task t : tasks) {
MyRunnable runnable = new MyRunnable(WHAT SHOULD GO HERE?, t)
executor.execute(runnable);
}
我不知道执行程序将分配哪个线程来运行给定任务,所以我不知道应该向可运行对象提供哪个 BufferedWriter。如何确保 ExecutorService 管理的每个线程都与一个对象(在本例中为 BufferedWriter)相关联?