java - 如何使用PrintWriter和flush()在文本文件上打印内容?

标签 java multithreading thread-safety printwriter

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

public void run() {

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

有人告诉我我应该使用PrintWriter和flush()或类似的东西,但我不知道如何使用它..有人可以帮助我吗? (“myRow”是我想在文本文件中写入的行号,每个人都在不同的行中)

非常感谢!!

最佳答案

I want to be sure that every line get calculated JUST one time,

我建议您使用 ExecutorService 并将每一行作为图像作业提交到线程池。请参阅底部的代码示例。如果你这样做正确,那么你就不需要担心会有多少输出行。

I could make a System.out.println(CalculatedLineNumber)

我不太明白这个的必要性。这是某种会计文件来帮助您确保所有图像都已得到处理吗?

Someone told me that I should use a PrintWriter and flush()

您不需要刷新 PrintWriter,因为它已经在下面同步了。只需在每个作业结束时打印出结果,如果您向 threadPool 提交了 X 行作业,那么您将获得 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(...);
    }
}

关于java - 如何使用PrintWriter和flush()在文本文件上打印内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10986318/

相关文章:

java - IllegalAnnotationsException SetMultimap 是一个接口(interface),JAXB 无法处理接口(interface)

java - 如何制作可读/写文件的可运行 JAR 文件?

c# - 显示非线程安全任务的 “Please Wait”对话框

c# - SqlConnection 线程安全吗?

Java - 读取和写入在浏览器窗口内呈现的 Pdf

java - Apache 的 HttpAsyncClient 在执行后永远不会返回

线程切换上的 Python 段错误

c++ - 如何开始使用多线程编程?

c# - 部分线程安全的字典

c - 在多线程程序中为 system() 向下传递信息