我想确保每一行都只计算一次,
我建议您使用 aExecutorService
并将每一行作为图像作业提交到线程池。请参阅底部的代码示例。如果你做对了,那么你就不必担心会有多少输出线。
我可以做一个System.out.println(CalculatedLineNumber)
我不太明白这样做的必要性。这是某种会计文件来帮助您确保所有图像都已处理吗?
有人告诉我应该使用 PrintWriter 和 flush()
你不需要flush
aPrintWriter
因为它已经在下面同步了。只需在每个作业结束时打印出结果,如果您向您提交了 X 行作业, threadPool
那么您将有 X 行输出。
您需要做的就是使用PrintWriter
:
PrintWriter printWriter = new PrintWriter(new File("/tmp/outputFile.txt"));
// each thread can do:
writer.println("Some sort of output: " + myRow);
下面是一些示例代码来展示如何使用ExecutorService
线程池。
PrintWriter outputWriter = ...;
// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// i'm not sure exactly how to build the parameter for each of your rows
for (int myRow : rows) {
// something like this, not sure what input you need to your jobs
threadPool.submit(new ImageJob(outputWriter, myRow, getHeight(), getWidth()));
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
...
public class ImageJob implements Runnable {
private PrintWriter outputWriter;
private int myRow;
private int height;
private int width;
public MyJobProcessor(PrintWriter outputWriter, int myRow, int height,
int width, ...) {
this.outputWriter = outputWriter;
this.myRow = myRow;
this.height = height;
this.width = width;
}
public void run() {
image.setRGB(0, myRow, width, 1, renderLine(myRow), 0, 0);
outputWriter.print(...);
}
}