如果我在 java 中使用线程,如何打印到文本文件?

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) );
}

为了回答您的问题,您有多个线程执行您的 运行 方法,所有线程都将写入名为 "Time.txt" 的文件。您应该为每个线程编写一个文件。此外,您还在多个线程之间共享输出流,这本身就是一个问题。在 运行 方法中移动 print writer 创建并使用像 "time" + Thread.curentThread().getID() + ".txt" 这样的名称。那应该解决它。