java - 多线程将相同的内容写入同一个文件?

标签 java synchronized

我一直认为并发线程写入同一个文件需要同步。

当多线程在不同步的情况下将相同的内容写入同一个文件时会发生什么?我想输出文件一定不完整或损坏。

public class Test 
{   
  public Runnable createLayoutRunnable() {
    return new Runnable() {
        public void run() {
            try {
                FileInputStream inputStream = new FileInputStream("mov.mp4");

                FileOutputStream outputStream = new FileOutputStream("mov_co.mp4");
                //IOUtils.copy(inputStream, outputStream);

                //synchronized ("lock"){
                int read = 0;
                byte[] bytes = new byte[1024];

                while ((read = inputStream.read(bytes)) != -1) {
                    outputStream.write(bytes, 0, read);
                }
                //}

                System.out.println(Thread.currentThread().getName() + " is done"); 



            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
}


public static void main(String[] args) {
    Test test = new Test();
    //Create Thread Pool for parallel layout
    ExecutorService executor = Executors.newFixedThreadPool(9);

    //Run Tasks and wait for termination in the current thread
    Future<?> f1 = executor.submit(test.createLayoutRunnable());
    Future<?> f2 = executor.submit(test.createLayoutRunnable());
    Future<?> f3 = executor.submit(test.createLayoutRunnable());
    Future<?> f4 = executor.submit(test.createLayoutRunnable());
    Future<?> f5 = executor.submit(test.createLayoutRunnable());
    Future<?> f6 = executor.submit(test.createLayoutRunnable());
    Future<?> f7 = executor.submit(test.createLayoutRunnable());
    Future<?> f8 = executor.submit(test.createLayoutRunnable());
    Future<?> f9 = executor.submit(test.createLayoutRunnable());


    try {
        f1.get();
        f2.get();
        f3.get();
        f4.get();
        f5.get();
        f6.get();
        f7.get();
        f8.get();
        f9.get();


    } catch (Exception ex) {
        ex.printStackTrace();
    }
    executor.shutdown();

    System.out.println("all done");

}

}

惊喜!输出的mov很好玩! 怎么会?请帮忙!

编辑:首先,我对造成的困惑感到非常抱歉。是的,我发布的第一次代码是同步的,而不是我所说的。我现在已经评论掉了。这是因为我正在研究代码,在那里我发现它是否同步并不重要,并且想知道为什么。

最佳答案

在这种特定情况下,您将输入文件中的相同内容写入输出文件中的相同位置。这就是所谓的 idempotent操作,同步与否并不重要。

如果每个线程编写自己的源文件(并且您消除了同步),您会看到(1)一个线程获胜,或者(2,更有可能)您会得到交错(损坏)的内容。

关于java - 多线程将相同的内容写入同一个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717397/

相关文章:

java - 使标记带有单击时使用的自定义信息(Android,Google Maps v2)

java - 使用 Java 生成 PowerPoint 2007/2010 文件

java - JBoss EAP 6.2 JMX 服务器和注册表绑定(bind)

java - 内部 Java 同步静态方法 : happens before relationship for static variable

java - 当同步方法正在执行时,非同步方法是否会阻塞

java - 同步对象: Locking Code vs Locking Object

java - 使用 Java 从网页中提取数据?

java - 有没有办法配置 Jersey 客户端请求日志记录的级别?

java - 测试方法是否以同步方式运行

java - 当线程进入 Java 中的同步块(synchronized block)/方法时到底发生了什么