我必须“暂停”我的应用程序,直到套接字收到来自其他应用程序的某个消息。
public class Status {
public static boolean ready = false;
}
public class Application
{
public void method()
{
// do job
// wait other app is ready
while(Status.ready == false)
{
// do nothing
// [[ 1 ]]
}
// continue
}
}
public class SocketImpl extends Thread
{
...
// It is expected that the other program is ready
public void run()
{
// receive some msg
// if it's ready message
Status.ready = true;
}
}
好的,我想你明白我做了什么,现在有两个问题
// [[ 1 ]]
替换为System.out.println(Status.ready)
它有效?添加println
允许while
来检测状态的变化。为什么?我无法解释这一点。
答案 0 :(得分:4)
这种忙碌的等待方式并不好。你应该实现 Observer 模式,这样当SocketImpl有一条消息时它会通知它附加的观察者。
首先定义一个观察者界面:
interface SocketObserver {
public void MessageReceived(Object aMessage);
}
其中aMessage可能是包含消息数据的自定义类的实例。
然后在你的SocketImpl中定义一个观察者(可以使用arraylist支持muliple)
public class SocketImpl extends Thread
{
private SocketObserver observer;
public void setObserver(SocketObserver observer) {
this.observer = observer;
}
// It is expected that the other program is ready
public void run()
{
// receive some msg
// if it's ready message
observer.MessageReceived(yourMessageHere); //Notify the observer that a message is received
}
}
然后在开始线程之前,设置observer属性。
SocketImpl socket = new SocketImpl();
socket.setObserver(new SocketObserver() {
@Override
public void MessageReceived(Object message) {
//Message received do something with it
}
});
socket.start();
您可以在此处查看有关实施观察者模式的更多信息: http://en.wikipedia.org/wiki/Observer_pattern