[英]How to print to a text file if I'm using threads in java?
在使用线程时,我不知道如何打印到文本文件,因为每次它仅创建另一个文件时,我最终只有一个结果,即最后一个,我已经尝试了很多事情,并且总是一样。
这只是代码的一部分,除了打印到文件之外,我还必须打印一个图,而且我也遇到同样的问题,因为它为每个线程创建一个图。
public class Adsda implements Runnable{
private int id=0;
public int number;
public String file="Time.txt";
private final PrintWriter outputStream;
public Adsda(int id) throws FileNotFoundException {
this.id=id+1;
this.outputStream=new PrintWriter(this.file);
}
public void run() {
int i,fact=1;
this.number=id;//It is the number to calculate factorial
long A=System.nanoTime();
for(i=1;i<=this.number;i++){
fact=fact*i;
}
long B=System.nanoTime();
long t=B-A;
double tt = (double)t / 1000000000.0;
System.out.println("Factorial of "+number+" is: "+fact+" Time: "+tt);
this.outputStream.println("Factorial of: "+this.number+" Time: "+tt);
this.outputStream.flush();
}
public static void main(String[] args) throws FileNotFoundException{
ExecutorService executor = Executors.newFixedThreadPool(2);//creating a pool of 2 threads
for(int i=0;i<5;i++){
executor.submit(new Adsda(i) );
}
executor.shutdown();
}
您应该创建一个PrintWriter
并通过在构造函数中传递它与线程共享,而不是让每个线程创建自己的PrintWriter
(和文件)。 尽管那样会导致文件中包含奇怪顺序的结果。 如果要按特定顺序排列它们,则应让线程将它们的结果输出到它们自己的缓冲区中,并且当所有线程完成后,按顺序将缓冲区写出到文件中。
PrintWriter pw = new PrintWriter(filename);
for(int i=0;i<5;i++){
executor.submit(new Adsda(i, pw) );
}
只是为了回答您的问题,您有多个执行您的run方法的线程,所有线程都将写入名为“ Time.txt”的文件。 您应该为每个线程编写一个文件。 另外,您正在多个线程之间共享输出流,这本身就是一个问题。 在run方法中移动打印编写器的创建,并使用“ time” + Thread.curentThread()。getID()+“。txt”之类的名称。 那应该解决它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.