2013-10-29 18 views
0

我正在使用swing工作線程來傳遞其餘服務。我的scenerio是我調用一個線程從休息服務獲取數據並添加到我的列表變量。 和另一個線程來推送數據列表來保存它。如何處理此之情況與線程安全如何在線程安全的多個swing工作線程中使用實例變量?

我的示例代碼如下

private LinkedList<LinkInfo> ***linkInfoList*** = new LinkedList<FlowLinkEntry>(); 

SwingWorker<LinkInfo, Void> loadLinkInfoThread = new SwingWorker<LinkInfo, Void>() { 

     @Override 
     protected LinkInfo doInBackground() throws Exception { 

      InputStream is = new URL("Http://URL").openStream(); 
      try { 
       BufferedReader reader = new BufferedReader(
         new InputStreamReader(is, 
           Charset.forName("UTF-8"))); 
       LinkInfo linkInfo = (LinkInfo)JsonConverter 
         .fromJson(reader, LinkInfo.class); 
       ***linkInfoList*** .add(linkInfo); 

      } finally { 
       is .close(); 
      } 
      return linkInfo; 
     } 
} 


SwingWorker<Void, Void> saveLinkInfoThread = new SwingWorker<Void, Void>() { 

     @Override 
     protected Void doInBackground() throws Exception { 
      //post data to particular url 
      //linkInfoList data is posting in this thread 

      URL url = new URL(http://url); 
      URLConnection conn = url.openConnection(); 
      conn.setDoOutput(true); 
      OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
      wr.write(***linkInfoList***); 
      wr.flush(); 
      // Get the response 
      BufferedReader rd = new BufferedReader(new InputStreamReader(
      conn.getInputStream())); 

     } 

}

我的問題是

  1. 如何linkInfoList數據存儲爲請求順序明智? (即)如果我多次調用加載線程,數據應該插入列表請求明智。

  2. 如何將等待狀態保存線程如果負載線程 已經在進行中。我的意思是,如果負載線程處於 運行狀態,完成負載線後,則僅保存線程應該具有運行

+0

使用同步塊,也許? –

+0

嘗試使用CopyOnWriteArrayList(http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html) – alex2410

+0

嗨,如果我在那時調用兩個線程,我想運行此完成加載線程後保存線程。當我使用同步的時候可以嗎? – Murali

回答

1

我會在初始化爲Oracle says同步列表。

List ***linkInfoList*** = Collections.synchronizedList(new LinkedList(...)); 

然後,你將不得不測試列表,如果有任何項目要保存,否則等待。

SwingWorker<Void, Void> saveLinkInfoThread = new SwingWorker<Void, Void>() { 

    @Override 
protected Void doInBackground() throws Exception { 

     List info = new ArrayList(); 
     while (***linkInfoList***.isEmpty()){ 
      Thread.currentThread().sleep(1000); 
     } 
     while (!***linkInfoList***.isEmpty()){ 
      info.add(***linkInfoList***.remove(0)); 
     } 



     //post data to particular url 
     //linkInfoList data is posting in this thread 

     URL url = new URL(http://url); 
     URLConnection conn = url.openConnection(); 
     conn.setDoOutput(true); 
     OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 


     wr.write(info); 
     wr.flush(); 
     // Get the response 
     BufferedReader rd = new BufferedReader(new InputStreamReader(
     conn.getInputStream())); 

    } 
相關問題