2012-03-03 13 views
0

如何在java中使用相同的程序發送和接收數據?更糟糕的是,我需要在同一時間同時進行這兩項操作。如何使相同的程序像服務器和客戶端一樣工作(使用java中的套接字)

+2

您使用的標籤表明您明白您需要使用多個線程;除此之外,沒有特別的技巧。你有沒有需要幫助的具體問題? – 2012-03-03 21:40:40

+0

是的,將發送和接收部分放在單獨的線程中(並且進一步使服務部分多線程以便爲多個客戶端服務)工作?這是處理這種情況的正常方式嗎? – Chani 2012-03-03 21:44:36

+0

@ return0請不要忘記,在JVM中,不會保證不間斷的線程生命週期。他們總是有可能被暫停,取消優先,重新開始等等。這會在某些時候破壞一些東西。 – 2012-03-03 21:52:38

回答

2

您需要一個行爲良好的隊列,例如兩個Thread之間的BlockingQueue

public class TwoThreads { 
    static final String FINISHED = "Finished"; 
    public static void main(String[] args) throws InterruptedException { 
    // The queue 
    final BlockingQueue<String> q = new ArrayBlockingQueue<String>(10); 
    // The sending thread. 
    new Thread() { 
     @Override 
     public void run() { 
     String message = "Now is the time for all good men to come to he aid of the party."; 
     try { 
      // Send each word. 
      for (String word : message.split(" ")) { 
      q.put(word); 
      } 
      // Then the terminator. 
      q.put(FINISHED); 
     } catch (InterruptedException ex) { 
      Thread.currentThread().interrupt(); 
     } 
     } 
     { start();} 
    }; 
    // The receiving thread. 
    new Thread() { 
     @Override 
     public void run() { 
     try { 
      String word; 
      // Read each word until finished is detected. 
      while ((word = q.take()) != FINISHED) { 
      System.out.println(word); 
      } 
     } catch (InterruptedException ex) { 
      Thread.currentThread().interrupt(); 
     } 
     } 
     { start();} 
    }; 
    } 
} 
相關問題