我想,以确保每一行计算得到仅一次,
我会建议你使用ExecutorService
,并提交各行作为一个形象的工作,线程池。查看代码示例的底部。如果你这样做,那么你不必担心会有多少输出线。
我可以做一个System.out.println(CalculatedLineNumber)
我不太明白这样做的必要性。这是一种会计档案,可以帮助你确保所有的图像都被处理了吗?
有人告诉我,我应该要用PrintWriter和flush()
,因为它已经下同步你并不需要一个flush
PrintWriter
。只需在每项工作结束时打印结果,并且如果您将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(...);
}
}
我想你需要['RandomAccessFile'(http://docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html)。 –