简体   繁体   English

如何在不中断的情况下通过多个线程写入CSV文件?

[英]How to write CSV file by multiple threads without any interruption between threads?

I have noticed that there are some data missing or data merged when I am trying to write CSV file by multiple threads at the same time. 我注意到在尝试同时由多个线程写入CSV文件时,某些数据丢失或数据合并。 So how could I avoid this missing or wrong data? 那么如何避免这种丢失或错误的数据呢?

My suggestion is to create a writer handler outside threads and sync the println/write method, like this: 我的建议是在线程外创建一个writer处理程序并同步println / write方法,如下所示:

package snippet;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MultiThreadWriter implements Runnable {
    private SyncWriter sw;

    public MultiThreadWriter(SyncWriter sw) {
        this.sw = sw;
    }

    public void run() {
        // ...
        sw.println("whatever");
        // ....
    }

    public static void main(String[] args) {
        SyncWriter writer = null;
        try {
            writer = new SyncWriter("foo.csv");
            ExecutorService pool = Executors.newFixedThreadPool(10);
            pool.submit(new MultiThreadWriter(writer));
            pool.submit(new MultiThreadWriter(writer));
            pool.submit(new MultiThreadWriter(writer));
            pool.submit(new MultiThreadWriter(writer));
            pool.submit(new MultiThreadWriter(writer));
            pool.submit(new MultiThreadWriter(writer));
            pool.submit(new MultiThreadWriter(writer));
            pool.shutdown();
            while (pool.awaitTermination(1000, TimeUnit.MILLISECONDS)) {
                ;
            }
            writer.close();
        } catch (Exception e) {
            // ..
        }
    }
}

class SyncWriter {
    private PrintWriter pw;

    public SyncWriter(String path) throws FileNotFoundException {
        pw = new PrintWriter(path);
    }

    public void close() {
        pw.close();
    }

    public synchronized void println(String x) {
        pw.println(x);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM