我有以下代码:
@Test
public void testMultipleUpdatesSameTime() {
final CyclicBarrier gate = new CyclicBarrier(3);
PrintStream out = null;
try {
out = new PrintStream(new FileOutputStream(
"C:\\pathToFile\\test2_output.txt"));
} catch (FileNotFoundException e1) {
System.err.println(e1);
}
System.setErr(out);
new Thread(() -> {
try {
gate.await();
} catch (InterruptedException e) {
System.err.println(e);
} catch (BrokenBarrierException e) {
System.err.println(e);
}
System.err.println("FROM1: Starting at: " + System.currentTimeMillis());
System.err.println("FROM1: Thread with ID: " + Thread.currentThread().getId());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println(e);
}
System.err.println("FROM1: Ending at: " + System.currentTimeMillis());
}).start();
new Thread(() -> {
try {
gate.await();
} catch (InterruptedException e) {
System.err.println(e);
} catch (BrokenBarrierException e) {
System.err.println(e);
}
System.err.println("FROM2: Starting at: " + System.currentTimeMillis());
System.err.println("FROM2: Thread with ID: " + Thread.currentThread().getId());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.err.println(e);
}
System.err.println("FROM2: Ending at: " + System.currentTimeMillis());
}).start();
System.err.println("NOTHING YET");
try {
Thread.sleep(10000);
gate.await();
} catch (InterruptedException e) {
System.err.println(e);
} catch (BrokenBarrierException e) {
System.err.println(e);
}
System.err.println("DONE");
}结果文件只包含预期输出的一半:
您是否知道为什么文件不包含“结束时”或异常?
发布于 2018-03-19 14:06:30
如果写完文件后不关闭文件,文件会丢失一些内容,这是很常见的情况。许多finalizer()子类中都有关闭流的OutputStream方法,但它们并不总是有机会像这里这样被调用。
主线程释放大门并立即退出,其他线程迅速运行,此时VM关闭,您不能相信事情已正确完成。
原始代码是复杂的,很难“修复”从地面上被打破的东西。例如,在实际代码中,不会有两个线程竞相写入同一个文件。这根本没道理。
在任何情况下,对此最好的“修复”将是主线程等待其他线程完成(而不是休眠),然后按下面的方式关闭文件。
Thread t1 = new Thread(() -> ...
Thread t2 = new Thread(() -> ...
t1.start();
t2.start();
t1.join();
t2.join();
out.close();https://stackoverflow.com/questions/49363812
复制相似问题