首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >System.out.println/System.err.println不工作

System.out.println/System.err.println不工作
EN

Stack Overflow用户
提问于 2018-03-19 13:09:36
回答 1查看 428关注 0票数 1

我有以下代码:

代码语言:javascript
复制
  @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");
  }

结果文件只包含预期输出的一半:

  • 还没什么
  • 完成
  • FROM1:从1521464569722开始
  • FROM2:从1521464569722开始
  • FROM1: ID: 11的线程
  • FROM2: ID: 12的线程

您是否知道为什么文件不包含“结束时”或异常?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-19 14:06:30

如果写完文件后不关闭文件,文件会丢失一些内容,这是很常见的情况。许多finalizer()子类中都有关闭流的OutputStream方法,但它们并不总是有机会像这里这样被调用。

主线程释放大门并立即退出,其他线程迅速运行,此时VM关闭,您不能相信事情已正确完成。

原始代码是复杂的,很难“修复”从地面上被打破的东西。例如,在实际代码中,不会有两个线程竞相写入同一个文件。这根本没道理。

在任何情况下,对此最好的“修复”将是主线程等待其他线程完成(而不是休眠),然后按下面的方式关闭文件。

代码语言:javascript
复制
Thread t1 = new Thread(() -> ...
Thread t2 = new Thread(() -> ...
t1.start();
t2.start();

t1.join();
t2.join();
out.close();
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49363812

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档