簡體   English   中英

System.out.println / System.err.println不起作用

[英]System.out.println/System.err.println not working

我有以下代碼:

  @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");
  }

結果文件僅包含預期輸出的一半:

  • 還沒有
  • DONE
  • FROM1:開始於:1521464569722
  • FROM2:開始於:1521464569722
  • FROM1:ID為11的線程
  • FROM2:ID為12的線程

您是否知道為什么文件不包含“結尾為”或異常?

如果您在寫入后不關閉文件,則文件丟失某些內容的情況很常見。 許多OutputStream子類中都有finalizer()方法,它們確實關閉了流,但是,在這種情況下,它們並不總是有被調用的機會。

主線程釋放閘門並立即退出,其他線程迅速運行,此時虛擬機已關閉,您不能相信事情能正確完成。

原始代碼令人費解,很難“修復”從頭開始的問題。 例如,在真實代碼中,您不會有2個線程競爭寫入同一文件中。 那只是沒有道理。

無論如何,最好的“解決方案”是讓主線程等待其他線程完成(而不是休眠),然后按如下所示關閉文件。

Thread t1 = new Thread(() -> ...
Thread t2 = new Thread(() -> ...
t1.start();
t2.start();

t1.join();
t2.join();
out.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM