[英]Why write() method of OutputStream class doesn't work in the console?
[英]OutputStream doesn't work with Threads
您能帮我解决下一个问题吗? 我试图将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();
}
完成后,关闭main中的打印流。 如果主线程在所有线程终止后终止,然后干净地关闭流,那将是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.