有效地监视int值

n00*_*ant 2 java swing

我将代码更改为更详细的版本,以便您可以更好地了解我的问题.

我需要"观察"一个整数值并立即响应它何时发生变化.到目前为止,我发现最好的方法是在无限循环中使用线程.

以下是我项目中极为简化的部分.总而言之,通过单击Bubble类中的按钮将notificationValue设置为1.我需要applet能够监视此notificationValue并在其发生更改时进行响应.

这是我的小程序:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的班级:

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);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

但很明显,这会使CPU保持在100%并且根本没有效率.什么是更好的方法来做到这一点?(假设我无法更改任何负责更改整数的方法.)

G_H*_*G_H 7

如果该int恰好是JavaBean的属性,则可以使用PropertyChangeListener.

但是,我怀疑如果您需要监视某个整数值以进行值更改,那么您就会遇到设计问题.最好确保只能通过某种方法更改整数,并确保该方法根据旧值和新值处理所需的逻辑.


Mic*_*rdt 7

当它发生变化时立即做出反应

这需要"立竿见影"吗?Thread.sleep(10)在while循环中添加一个可能会将CPU负载降低到接近零.

什么是更好的方法来做到这一点?(假设我无法更改任何负责更改整数的方法.)

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