我一直认为并发线程写入同一个文件需要同步。
当多线程在没有同步的情况下将相同的东西写入同一个文件时会发生什么?我想输出文件一定是不完整或损坏的。
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很好玩!怎么来的?请帮忙!
编辑:首先,我对混乱感到非常抱歉。是的,我发布的第一次代码是同步的,而不是我所说的。我现在已经评论了。这是因为我在玩代码,这就是我发现它是否同步无关紧要的地方,我想知道为什么。