不断检查Java中的变化?
如何检查布尔值在给定时间段内更改状态,以及如果在该时间段内发生更改则执行方法?
请用 Java 提供任何帮助吗?
谢谢。
How can I check for a boolean to change state over a given period of time, and if a change is made over that time period perform a method?
Can any help please be given in Java.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
似乎您应该考虑实现某种
模型视图控制器模式
。看看这里
基本的想法是,当布尔值被更改,然后该事件被触发,您的侦听器应该处理该事件。
Seems like you should look to implement some sort of
Model View Controller Pattern
.Have a look here
The basic idea is that you should fire an event when the boolean is changed, and then that event is fired, your listener should handle that.
听起来你想将一个布尔值包装在一个类中,你可以监听它的变化。
然后简单地做:
这实际上是MVC模式(和观察者模式)的一个简单案例。本例中的模型是 ObservableBoolean,视图是想要收到更改通知的“视图”。
如果您想避免看起来奇怪的
javax.swing...
导入,您也可以编写自己的ChangeListener
接口Sounds like you want to wrap a boolean in a class which you can listen for changes on.
Then simply do:
This is actually a simple case of the MVC pattern (and the observer pattern). The model in this case is the ObservableBoolean and the view would be the "view" that wants to be notified of the changes.
You could also write your own
ChangeListener
interface if you want to avoid a strange lookingjavax.swing...
import最简单的方法是使用包装类...
这是 Swing 中的常见模式,您可以使用 PropertyChangeSupport 简化了您可以观察和监听属性更改的对象的创建。使用此类,您可以注册 PropertyChangeListener 处理生成的 PropertyChangeEvent就是这个结果。
The easiest way to do this is with a wrapper class...
This is a common pattern in Swing, and you can use PropertyChangeSupport to simplify the creation of objects on which you can observe and listen for property changes. With such classes, you can register a PropertyChangeListener to handle the resulting PropertyChangeEvents that result.
使用
Timer
或编写您自己的类来扩展Thread
。谷歌搜索这些东西应该会给你一个良好的开始
编辑:从问题来看,还不清楚他的意图是什么。也许他想在确切的时间段内调用某些方法,而不是在事件发生后立即调用。对于这种模式,我仍然宁愿坚持使用计时器,或者编写自己的线程。编写自己的线程仍然是解释特定用户需求的最佳方式。另一方面,如果这确实是监听事件的情况,那么我的计时器模式将是完全错误的。
示例:如果用户请求的话(reques = true),我想每 5 分钟更新一次数据库(想象一下网页浏览器游戏)。如果请求错误,我不需要更新数据库。立即更新数据库(有数千名玩家的《部落战争》游戏中的统计数据)完全是矫枉过正。
use
Timer
or write your own class extendingThread
.Googling those things should give you good start
edit : From question it is not quite clear what are his intends. Maybe he wants to invoke some method in exact period of time, not immediatelly after event. For this pattern, I'd still rather stick to timer, or write my own Thread. Writing own Thread is still best way of interpreting specific user requirements. On the other hand, if this is really case of listening to events, my Timer pattern would be completely wrong.
example : I want to update database (imagine web browser game) every 5 minutes, if users requests so (reques = true). With false request, I don't need to update database. Immediatelly update database (f.e. stats in game Tribal Wars with thoushands of players) is totally overkill.