2017-02-19 130 views
0

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

回答

0

你应该建立一个单一的PrintWriter,并通过它传递在构造函数中,而不必每个线程创建自己的PrintWriter(和文件)与线程共享。尽管这会导致包含奇怪顺序结果的文件。如果你想让它们按照特定的顺序存在,你应该让这些线程将结果输出到它们自己的缓冲区中,当所有的线程完成时,将缓冲区依次写入文件中。

PrintWriter pw = new PrintWriter(filename); 

for(int i=0;i<5;i++){ 
    executor.submit(new Adsda(i, pw)); 
} 
0

只是为了回答你的问题,你有你的执行run方法,他们都将编写一个名为“TIME.TXT”文件多线程。你应该为每个线程写一个文件。你也在多线程之间共享你的输出流,这本身就是一个问题。在run方法中移动打印作者创建,并使用“time”+ Thread.curentThread()。getID()+“.txt”之类的名称。这应该解决它。