您如何在不忙于等待的情况下暂停线程直到条件变为真? [英] How do you pause a thread until a condition becomes true without busy waiting?

查看:184
本文介绍了您如何在不忙于等待的情况下暂停线程直到条件变为真?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不忙等待的情况下暂停线程直到条件变为真? 例如,假设我正在检查

How do you pause a thread until a condition becomes true without busy waiting? For example, suppose I'm checking to see whether

playerOne.isWalking()

playerOne.isWalking()

这将是真实的,并且当它变为真实时,我想运行一些代码.再次假设playerOne是Player类的实例,然后该类具有isWalking()函数.我无法访问使isWalking()变为true的内容.因此,每次我要检查isWalking()是否为true时,都必须从player实例中显式调用该方法.

Is going to be true and I want to run some code when it does become true. Again suppose playerOne is an instance of the class Player which then has the function isWalking(). I do not have access to the what makes isWalking() become true. So everytime I want to check to see if isWalking() is true, I have to call the method from an instance of player explicitly.

我已经尝试在同步块中使用Wait/Notify,但这将永远无法正常工作,因为当isWalking()变为true且我不知道何时将变为true时,我必须手动通知线程唤醒

I've tried using Wait/Notify in synchronized blocks but that wouldn't ever work because I would have to manually notify the Thread to wake up when isWalking() becomes true and I don't know when it will become true.

我尝试使用观察者模式使Player成为可观察的子类,以便在isWalking()变为true时可以调用update方法,但是我也不知道何时会发生.

I've tried using the observer pattern to make Player a subclass of observable so that I can call the update method when isWalking() becomes true but again I don't know when that will happen.

我什至尝试使用属性,但这也不起作用.

I've even tried using Propertys but that wouldn't work either.

甚至无需等待就可以检查吗?不断轮询并调用该函数以查看其是否为真,然后,如果它为真,则执行代码.

Is this even possible to check without busy-waiting? Constantly polling and calling that function to see if it is true, then if it is true, execute the code.

这是我在忙碌等待中做出的糟糕解决方案:

This was a bad solution I made involving busy-waiting:

忙等待解决方案

推荐答案

潜在的问题是您使用 getter 方法获取信息并对其进行操作.此处违反的原则是告诉,不要问!.

The underlaying problem is that you use a getter method to aquire an information and act on it. The principle which is violated here is Tell, don't ask!.

OO解决此问题的方法是引入接口(例如:PlayerMovingListener).

The OO whay to solve this is to introduce an interface (e.g.: PlayerMovingListener).

player类将包含实现该接口的对象的实例(或它们的列表).播放器一开始走动,就会调用由播放器所拥有的(或所有)侦听器对象实现的接口中定义的isMoving()方法.
很可能是由当前Payer实现中的setter方法触发的.

The player class would hold an instance of an object implementing that interface (or a list of them). As soon as the player starts walking it calls the isMoving() method defined in the interface implemented by the (or all) listener object(s) held by the player.
Most likely is triggered by a setter method in your current Payer implementation.

这篇关于您如何在不忙于等待的情况下暂停线程直到条件变为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆