简体   繁体   中英

How to print to a text file if I'm using threads in java?

I don't know how to print to a text file when I'm using threads because every time it just creates another file, so I end up with just one result which is the last one, I have tried a lot of things and is always the same.

This is just a part of the code, besides printing to the file I have to print a graph too and I have the same problem as it creates one graph for each thread.

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

You should create a single PrintWriter and share that with the threads by passing it in the constructor instead of having each thread create their own PrintWriter (and file). Although that will result in the file containing the results in weird order. If you want to have them in a specific order, you should have the threads output their results in their own buffers and when all threads are finished, write the buffers out to a file in sequence.

PrintWriter pw = new PrintWriter(filename);

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

Just to answer your question, you have multiple threads that execute your run method and all of them will write the file named "Time.txt". You should write a file for each thread. Also you are sharing your output stream between multiple threads which is an issue in itself. Move the print writer creation in the run method and use a name like "time" + Thread.curentThread().getID() + ".txt". That should fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM