你能帮我解决下一个问题吗?我正在尝试将 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();
}
}
和另一个类的主要方法
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();
}