0

次の問題を解決するのを手伝ってもらえますか?スレッドでPrintStreamを使用して、スレッドがさまざまな出力に何かを書き込むようにしようとしています。問題は次のとおりです。System.outは完全に機能しますが、追加しようとすると

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

私のスレッドは何も書きたくありません。通常の印刷がmain()メソッドである間は、警告や例外はスローされません。

filePRinPrintStream.println("PREVED");

これがあなたの情報のための私のコード抜粋です。

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();
    }

}

および別のクラスのmainメソッド

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();
    }
4

1 に答える 1

0

完了したら、メインでプリントストリームを閉じます。すべてのスレッドが終了した後にメインが終了し、そのときにストリームをきれいに閉じるとよいでしょう。

于 2013-02-02T14:25:17.487 に答える