2016-12-05 43 views
1

我正在一個項目和我的項目的一部分工作,我作爲字符串的ArrayList我保持記錄來保存來自其他互連繫統的傳入消息。這是一個點對點設計,所以我想讓BufferedReader準備好讀取任何套接字發送給系統的消息,所以我設計了一個線程,在創建時爲每個套接字創建一個新的線程,以便監聽特定的輸入流。什麼是使用線程更新ArrayList對象實例的好方法?

現在我已經使用以下兩種私有類嘗試這樣的:

InputListener(內部類ListenerThread)

private class InputListener implements Runnable{ 
     private ArrayList<String> queue; 
     private ArrayList<Stream> sockets; 
     private ArrayList<Thread> threads; 
     public InputListener(ArrayList<String> q, ArrayList<Stream> s) 
     { 
      this.queue = q; 
      this.sockets = s; 
      this.threads = new ArrayList<Thread>(); 
      for(int i = 0; i < this.sockets.size(); i++) 
      { 
       Thread t = new Thread(new ListeningThread(this.sockets.get(i).is, this.queue)); 
       t.start(); 
       threads.add(t); 
      } 
     } 
     private class ListeningThread implements Runnable{ 
      private BufferedReader read; 
      private ArrayList<String> queue; 
      private boolean status; 
      public ListeningThread(InputStream is, ArrayList<String> q) 
      { 
       this.read = new BufferedReader(new InputStreamReader(is)); 
       this.queue = q; 
       status = true; 
      } 
      @Override 
      public void run() { 
       while(true) 
       { 
        String str = ""; 
        try { 
         str += read.readLine(); 
         while(!str.equals("END")) 
          str += read.readLine(); 
         this.queue.add(str); 
        } catch (IOException e) { 
        status = false; 
        break; 
       } 
      } 
     } 
    } 
    @Override 
    public void run() { 
     while(status) 
      ; 
    } 
} 

private class Stream{ 
    public InputStream is; 
    public OutputStream os; 
    public Stream(final Socket s) 
    { 
     try { 
      this.is = s.getInputStream(); 
      this.os = s.getOutputStream();    
     } catch (IOException e) { 
      return; 
     } 
    } 

    public InputStreamReader getReader() 
    { 
     return new InputStreamReader(this.is); 
    } 

} 

當我創建InputListener我通過引用來自另一個類的隊列,我排除了這個類來防止這個問題複雜化,所以假設這個ArrayList被初始化了,並且它的指針(我不記得是什麼java調用它)通過。我的問題是,當我使用一個循環像下面,我就被困在一個無限循環

while(queue.size equals 0) 
    Do nothing 

Remove and do something with String at index 0 in queue 

誰能幫我解決這個問題?任何幫助將大大appriciated!

+0

你能根據提供的答案解決這個問題嗎? –

回答

1

您應該使用java.util.concurrent中的一個專用容器類而不是標準的非同步ArrayList。

例如,LinkedBlockingQueue

// in the setup 
BlockingQueue<String> queue = new LinkedBlockingQueue<>(); 

// in producer thread 
queue.put(work); 

// in consumer thread 
work = queue.take(); // blocking - waits as long as needed 

我還建議閱讀Concurrency上的Java教程。這不是一個小問題。