2016-03-15 238 views
-2

我有一個多線程服務器。服務器接受不同客戶端的連接。這些客戶端定期發送數據。我的服務器有一個標準的多線程代碼風格,如線程,運行方法等。但是,當我啓動客戶端時,它會發送數據,在此過程中,當我啓動另一個客戶端時,第一個線程停止,第二個線程開始將數據寫入其特定文件。換句話說,如何在JAVA中使用多線程來寫入不同文件的數據?

預期結果:

第一線程的時間--->在FILE1.TXT10秒數據, 第二線程的持續時間--->在FILE2.TXT10秒數據,

實際結果:

第一線程的時間--->只有3在FILE1.TXT10秒數據秒,(I開始第二線程開始第一線程後3秒) 第二線程的持續時間 - - > 10秒鐘的數據在f ile2.txt

反之亦然。

我想用多線程編寫不同的多個文件。

你能幫我解決這個問題嗎?

謝謝。

這裏是我的代碼:

public void run() { 
     PrintWriter outputStream = null; 
     try { 

      int x=0; 
      while (runThread) { 
       FileOutputStream output = new FileOutputStream(getRootDirectory() + fileName, true); 
       for (int i = 17; i < requestData.length; i++) { 
        output.write(requestData[i]); 
       } 
       output.close(); 

       if (!ServerOn) { 
        System.out.print("Server has already stopped"); 
        outputStream.println("Server has already stopped"); 
        outputStream.flush(); 
        m_bRunThread = false; 
       } 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       inputStream.close(); 
       outputStream.close(); 
       myClientSocket.close(); 
       System.out.println("...Stopped"); 
      } catch (IOException ioe) { 
       ioe.printStackTrace(); 
      } 
     } 
    } 
+0

請發表[最小,完整且可驗證的示例](http://stackoverflow.com/help/mcve)。 – MikeCAT

+0

如果您從多個線程寫入同一文件,則可能會發生損壞,您應該使用文件鎖定,或者使用自己的鎖定系統來防止此問題。 – Ferrybig

+0

使用多線程可以允許您a)減輕網絡延遲或b)如果你有更多的CPU,可以使用更多的CPU電源,但是它不會1)使你的網絡上傳速度更快2)讓你的磁盤更快地旋轉。你必須瞭解你的瓶頸是什麼時候使用多線程將會有所作爲。 –

回答

0

這是2乳寧線巫通用例U可以個性化它作爲u需要,我希望它能幫助

class RunnableDemo implements Runnable { 
    private Thread t; 
    private String threadName; 

RunnableDemo(String name){ 
    threadName = name; 
    System.out.println("Creating " + threadName); 
    } 
    public void run() { 
    System.out.println("Running " + threadName); 
    try { 
    for(int i = 4; i > 0; i--) { 
     System.out.println("Thread: " + threadName + ", " + i); 
     // Let the thread sleep for a while. 
     Thread.sleep(50); 
    } 
} catch (InterruptedException e) { 
    System.out.println("Thread " + threadName + " interrupted."); 
} 
System.out.println("Thread " + threadName + " exiting."); 
} 

public void start() 
{ 
    System.out.println("Starting " + threadName); 
    if (t == null) 
    { 
    t = new Thread (this, threadName); 
    t.start(); 
    } 
} 

} 

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

    RunnableDemo R1 = new RunnableDemo("Thread-1"); 
    R1.start(); 

    RunnableDemo R2 = new RunnableDemo("Thread-2"); 
    R2.start(); 
} 
} 
+0

非常感謝。爲我工作! –

相關問題