你能帮我解决下一个问题吗? 我正在尝试将PrintStream与我的Threads一起使用,以使它们能够将内容写入不同的输出。 问题是: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();
}
}
和另一个班级的主要方法
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();
}
答案 0 :(得分:0)
如果完成,请在main中关闭您的打印流。 如果主要在所有线程终止后终止,并且然后干净地关闭流,那将是一个好主意。