当我使用线程时,我不知道如何打印到文本文件,因为每次它只创建另一个文件,所以最终只有一个结果,这是最后一个结果,我尝试了很多东西并始终如一。如何使用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();
}