2013-02-20 110 views
-1

這是該方法,我想從該方法獲取變量數據以在另一個端口中使用它。從特定端口獲取數據

public synchronized void serialEvent(SerialPortEvent oEvent) { 
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { 
     try { 
      int available = input.available(); 
      byte chunk[] = new byte[available]; 
      input.read(chunk, 0, available); 

      // Displayed results are codepage dependent 

      data =new String(chunk); 

     } catch (Exception e) { 
      System.err.println(e.toString()); 
     } 
    } 
} 
+0

請正確地提出你的問題。你面臨的問題是什麼?這是一個數據被其他線程/方法讀取的問題嗎? – user1428716 2013-02-20 22:00:40

+0

此方法讀取我想在另一個類中使用的adata進行身份驗證等。 – 2013-02-21 00:46:03

回答

1

這取決於你想要達到的目的,最簡單的方法是直接從serialEvent調用其他方法(比如它的名字processData),並通過它,你從COM端口接收例如數據processData(new String(chunk));

這種方法的問題是,如果您的方法processData做了一些重的事情,它會阻止serialEvent

另一種方法是有一個單獨的thread來處理該數據,您可以與concurrent.BlockingQueue的實現進行通信。因此,在serialEvent內,您只需將數據推送至隊列,並繼續等待processData完成。

只需使用BlockingQueue搜索Producer/Consumer模式,就可以找到大量代碼示例。