有效地监控int值

问题描述:

我改变了代码,以更详细的版本,所以你可以得到我的问题的一个更好的主意。有效地监控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

立即回应时,它改变

如何“立竿见影”这是否需要准确地?在while循环中添加Thread.sleep(10)可能会将CPU负载降至接近零。

这将是一个更好的方式来做到这一点? (假设我不能更改任何负责更改整数的方法)。

更好的方法是不直接暴露字段。封装好处的一个很好的例子 - 使用setter方法会使实现观察者模式变得微不足道。

+0

上发生我已经尝试了Thread.sleep(10)并且它仍然保持非常高的状态。在我的项目中,我需要监视的整数封装在JPanel中,并使用getter/setter方法对其进行修改。由于我的项目编写方式,我不能那样做。我会尝试修改我的原始帖子,以便您可以获得更好的主意。 – n00neimp0rtant

尝试添加Thread.sleep(1);,以节省CPU。

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

不过,我怀疑,如果你需要监视的值变化的一些整数你有一个设计问题。最好确保只能通过某种方法更改整数,并确保该方法根据旧值和新值处理所需的逻辑。

您可以检查变量的值,以节省CPU时间。或者使用模式Observer

你能封装在另一个类的整数,具有setter和getter包裹,并添加一个通知(通过观察员)?

您可以使用wait/notify。您可以使用ExecutorService。很大程度上取决于您是否可以更改设置整数的代码。

+0

我不行。如果你想看看,我完全改变了我给出的代码示例,以便更好地了解为什么我必须这样做。 – n00neimp0rtant

假如你不能改变这实际上将没有什么可以做的整数代码。话虽这么说,如果你调用Thread.yield()在每年年底将线对其他应用程序的性能产生的影响将是最小的。