2011-11-03 55 views
2

我改變了代碼,以更詳細的版本,所以你可以得到我的問題的一個更好的主意。有效地監控int值

我需要「看」一個整數值,並立即向它的變化時作出反應。到目前爲止,我發現的最好方法是在無限循環中使用線程。

以下是我的項目大大簡化了一部分。總而言之,通過點擊我的Bubble類中的按鈕,notificationValue被設置爲1。我需要小程序能夠監視此通知值,並在其發生更改時作出響應。

這裏是我的小程序:

public class MyApplet extends JApplet 
{ 
    Bubble myBubble = new Bubble(); 
    public void run() 
    { 
     new Thread(
     new Runnable() { 
      public void run() { 
       while(true) { 
        if(myBubble.getNotificationValue() == 1) { 
         /* here I would respond to when the 
         notification is of type 1 */ 
         myBubble.resetNotificationValue; 
        } 
        else if(myBubble.getNotificationValue() == 2) { 
         /* here I would respond to when the 
         notification is of type 2 */ 
         myBubble.resetNotificationValue; 
        } 
        else if(myBubble.getNotificationValue() != 2) { 
         /* if it is any other number other 
         than 0 */ 
         myBubble.resetNotificationValue; 
        } 

        // don't do anything if it is 0 
       } 
      } 
     }).start(); 
    } 
} 

這裏是我的課:

public class Bubble extends JPanel 
{ 
    public JButton bubbleButton; 

    public int notificationValue = 0; 

    public int getNotificationValue() 
    { 
     return notificationValue; 
    } 
    public void resetNotificationValue() 
    { 
     notificationValue = 0; 
    } 

    protected void bubbleButtonClicked(int buttonIndex) 
    { 
     notificationValue = buttonIndex; 
    } 

    public Bubble() 
    { 
     bubbleButton = new JButton(); 
     bubbleButton.addActionListener(new ActionListener(){ 
      public void actionPerformed(ActionEvent event) 
      { 
       bubbleButtonClicked(1); 
      } 
     }); 
    } 
} 

但很明顯,保持了CPU高達100%,是效率不高的。什麼是更好的方法來做到這一點? (假設我不能改變任何負責改變整數的方法。)

+1

通常你會使用帶有脈衝的鎖來通知改變,所以等待的線程會喚醒,但是這需要一個對象鎖定並且能夠修改setter。但是這聽起來像你不能將注入功能注入setter? – AaronLS

+0

然而,你在你的線程中解決了這個邏輯問題 - 不要忘記訪問已實現的Swing組件的_any_屬性_必須在EDT – kleopatra

回答

7

立即迴應時,它改變

如何「立竿見影」這是否需要準確地?在while循環中添加Thread.sleep(10)可能會將CPU負載降至接近零。

這將是一個更好的方式來做到這一點? (假設我不能更改任何負責更改整數的方法)。

更好的方法是不直接暴露字段。封裝好處的一個很好的例子 - 使用setter方法會使實現觀察者模式變得微不足道。

+0

上發生我已經嘗試了Thread.sleep(10)並且它仍然保持非常高的狀態。在我的項目中,我需要監視的整數封裝在JPanel中,並使用getter/setter方法對其進行修改。由於我的項目編寫方式,我不能那樣做。我會嘗試修改我的原始帖子,以便您可以獲得更好的主意。 – n00neimp0rtant

1

嘗試添加Thread.sleep(1);,以節省CPU。

7

如果INT恰好是一個JavaBean的屬性,你可以使用一個PropertyChangeListener

不過,我懷疑,如果你需要監視的值變化的一些整數你有一個設計問題。最好確保只能通過某種方法更改整數,並確保該方法根據舊值和新值處理所需的邏輯。

0

您可以檢查變量的值,以節省CPU時間。或者使用模式Observer

0

你能封裝在另一個類的整數,具有setter和getter包裹,並添加一個通知(通過觀察員)?

2

您可以使用wait/notify。您可以使用ExecutorService。很大程度上取決於您是否可以更改設置整數的代碼。

+0

我不行。如果你想看看,我完全改變了我給出的代碼示例,以便更好地瞭解爲什麼我必須這樣做。 – n00neimp0rtant

0

假如你不能改變這實際上將沒有什麼可以做的整數代碼。話雖這麼說,如果你調用Thread.yield()在每年年底將線對其他應用程序的性能產生的影響將是最小的。