簡體   English   中英

如果我在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) );
}

只是為了回答您的問題,您有多個執行您的run方法的線程,所有線程都將寫入名為“ Time.txt”的文件。 您應該為每個線程編寫一個文件。 另外,您正在多個線程之間共享輸出流,這本身就是一個問題。 在run方法中移動打印編寫器的創建,並使用“ time” + Thread.curentThread()。getID()+“。txt”之類的名稱。 那應該解決它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM