2012-06-11 41 views
0

我正在使用多线程来计算图像。每一个线程计算一条线,当一个线程已经在计算线时,下一个线程是否应该在该线之后计算线一个线。但我想确保每一行只有一次计算,为了做到这一点,我可以创建一个System.out.println(CalculatedLineNumber),并在文本文件中输出,以便当我用文本打开它时编辑器,我会直接看到打印的行数是否与文本文件中的行数相同。但我应该怎么做? 这里是我在计算完成的run()方法的代码片段:如何使用PrintWriter和flush()打印文本文件上的内容?

public void run() { 

       int myRow; 
       while ((myRow = getNextRow()) < getHeight()) { 
        image.setRGB(0, myRow, getWidth(), 1, renderLine(myRow), 0, 0); 
       } 
      } 

有人告诉我,我应该要用PrintWriter和flush()或类似的东西,但我不知道怎么用那..任何人都可以帮助我呢? (“myRow”是我想要在文本文件上编辑的行号,并且每个人都在不同的行中)

Thankyou太多了!

+0

我想你需要['RandomAccessFile'(http://docs.oracle.com/javase/6/docs/api/java/io/RandomAccessFile.html)。 –

回答

1

我想,以确保每一行计算得到仅一次,

我会建议你使用ExecutorService,并提交各行作为一个形象的工作,线程池。查看代码示例的底部。如果你这样做,那么你不必担心会有多少输出线。

我可以做一个System.out.println(CalculatedLineNumber)

我不太明白这样做的必要性。这是一种会计档案,可以帮助你确保所有的图像都被处理了吗?

有人告诉我,我应该要用PrintWriter和flush()

,因为它已经下同步你并不需要一个flushPrintWriter。只需在每项工作结束时打印结果,并且如果您将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(...); 
    } 
} 
+0

嗨Gray, 感谢您的非常好的回答。但我认为我需要更容易:它只是while循环中的'System.out.println(myRow)'。但是在控制台上会有太多的线条,所以最好将这个输出放在Textfile中。我应该怎么做,没有太多复杂的事情:-)谢谢! – ZelelB

+0

呵呵。好。我已经添加了'PrintWriter'的用法。那是你需要的吗? – Gray

+0

是的,谢谢..但仍然存在一个问题:eclipse通过PrintWriter printWriter = new PrintWriter(new File(“outputFile.txt”));告诉“未处理的FileNotFoundException”。当我添加到“运行()”抛出FileNotFoundExcpetion eclipse告诉我remve that ..我该怎么办? – ZelelB

相关问题