2015-09-12 32 views
0

我有問題。我需要創建9個文件,每個文件都從線程名稱中調用。每個文件將被稱爲1.txt,2.txt,3.txt等。每個文件將填充與文件名稱相對應的符號(1.txt文件爲「1」)。每個文件應該是100行,每行長度爲100個字符。這項工作必須執行線程和I \ O。當使用多個線程時,我需要在生成的文件super.txt中讀取這些文件的內容。如何在多個線程中寫入文件

我的代碼:

public class CustomThread extends Thread { 

    Thread t; 
    String threadName; 

    CustomThread(String threadName) { 
     this.threadName = threadName; 
    } 

    @Override 
    public void run() { 
     if (t == null) { 
      t = new Thread(this); 
     } 
     add(threadName); 
    } 

    public void add(String threadName) { 
     File f = new File(threadName + ".txt"); 

     if (!f.exists()) { 
      try { 
       f.createNewFile(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
       System.out.println("File does not exists!"); 
      } 
     } 

     FileWriter fw = null; 
     try { 
      fw = new FileWriter(f); 
      for (int i = 0; i < 100; i++) { 
       for (int j = 0; j < 100; j++) { 
        fw.write(threadName); 
       } 
       fw.write('\n'); 
      } 

     } catch (IOException e) { 
      e.printStackTrace(); 
      System.out.println("File does not exists!"); 
     } 
    } 
} 

我的主:

public class Main { 
    public static void main(String[] args) { 

     CustomThread T1 = new CustomThread("1"); 
     T1.start(); 

     CustomThread T2 = new CustomThread("2"); 
     T2.start(); 

    } 
} 

第一個問題。我需要,循環制造線程。看看我的主要:我創建

CustomThread T1 = new CustomThread("1"); 
T1.start(); 

但是,我想在週期中創建9個文件。這個怎麼做 ?

第二個問題。我需要從多個線程寫入每個文件。

第三個問題。如何從結果文件中的多個線程寫入該文件的五個內容?

回答

1

我想循環創建9個文件。這個怎麼做 ?

使用循環

for (int i = 1; i <= 9; i++) { 
    new CustomThread("" + i).start(); 
} 

我需要在每一個我的文件從多個線程來寫。

你是如何做到這一點的?在啓動線程之前打開這些文件,並在您使用它們時將其鎖定。

如何從結果文件中的多個線程寫入該文件的五個內容?

你能改述這個問題嗎?

+0

如何從結果文件中的多個線程寫入?結果super.txt是包含所有文件的文件。 – Valeriu

+0

看看:http://stackoverflow.com/questions/10027020/write-to-text-file-from-multiple-threads –

+0

@Valeriu「打開文件(s),然後再啓動線程並鎖定它們你曾經使用它們。「你有什麼疑問? –