2013-02-02 37 views
0

你能幫我解決下一個問題嗎? 我正在嘗試使用PrintStream和我的線程來使它們寫入不同的輸出。 的問題是:System.out的完美的作品,但是當我嘗試添加OutputStream不支持線程

File f1 = new File("src/task7/simple/1.txt"); 
PrintStream filePRinPrintStream = new PrintStream(f1) 

我的主題不想寫東西,它拋出沒有警告或異常而普通的印刷是main()方法是OK 。

filePRinPrintStream.println("PREVED"); 

這裏是我的代碼摘錄您的信息。從另一個類

public static void main(String[] args) { 

     File f1 = new File("src/task7/simple/1.txt"); 

     try(PrintStream filePRinPrintStream = new PrintStream(f1)){ 

      //filePRinPrintStream.println("PREVED"); 
      NamePrinterIF thread2 = new NamePrinterThread(); 
      thread2.setCount(20); 
      thread2.setInterval(350); 
      thread2.setStream(filePRinPrintStream); 
      thread2.setPrintName("thread2"); 

      thread2.startThread(); 

      filePRinPrintStream.flush(); 
     } catch(IOException e){ 
      e.printStackTrace(); 
     } 

     NamePrinterIF thread1 = new NamePrinterThread(); 
     thread1.setCount(10); 
     thread1.setInterval(200); 
     thread1.setStream(System.out); 
     thread1.setPrintName("thread1"); 

     thread1.startThread(); 
    } 
+2

你在哪裏關閉你的printstream? – AlexWien

回答

0

public class NamePrinterThread implements Runnable, NamePrinterIF{ 

    private String name; 
    private PrintStream outputStream; 
    private long interval; 
    private int count; 

    @Override 
    public void setPrintName(String name) { 
     this.name = name; 
    } 

    @Override 
    public void setStream(PrintStream stream) { 
     if(stream == null) throw new NullPointerException("PrintStream is null"); 
     this.outputStream = stream; 
    } 

    @Override 
    public void setInterval(long ms) { 
     if(ms <= 0) throw new IllegalArgumentException("Printing interval can't be negative"); 
     this.interval = ms; 
    } 

    @Override 
    public void setCount(int count) { 
     if(count <= 0) throw new IllegalArgumentException("Printing count can't be negative"); 
     this.count = count; 
    } 

    @Override 
    public void run() { 
     for (int i = 0; i < this.count; i++) { 
      try { 
       outputStream.println(this.name); 
       Thread.sleep(interval); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     }  
    } 

    public void startThread(){ 
     new Thread(this, name).start(); 
    } 

} 

和主要方法,閉上你的PrintStream主,如果你做。 如果主線程在所有線程終止之後終止,並且您完全關閉流,那將是一個好主意。

+0

非常感謝您的幫助。它曾在去年 我已經改變了JDK 7的嘗試 - 以資源爲純老 嘗試{ } {趕上} 並不僅僅是像這樣在以後我run方法關閉流: 的OutputStream。沖洗(); outputStream.close(); –

+0

@JB Nizet在閱讀您的評論後更新 – AlexWien