我正在尝试将类用作 Observer 和 Observable。此类将作为线程运行。在 run() 方法中,线程将等待并在获取事件后通知线程。有示例代码:
public class Runner {
public static void main(String[] args) {
MyThread mt = new MyThread();
Controller c = new Controller();
mt.addObserver(c);
c.addObserver(mt);
Thread t = new Thread(mt);
t.start();
}
}
public class MyThread extends Observable implements Observer, Runnable {
static private Integer op = 0;
public void run() {
synchronized (this) {
while (true) {
op++;
System.out.println(op + " Thread started");
super.setChanged();
super.notifyObservers(new Object());
op++;
System.out.println(op + " Thread send event");
try {
op++;
System.out.println(op + " Thread wait");
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void update(Observable arg0, Object arg1) {
op++;
System.out.println(op + " Thread got event");
synchronized (this) {
op++;
System.out.println(op + " We are in synchronized block!");
this.notify();
}
}
}
public class Controller extends Observable implements Observer {
public void update(Observable arg0, Object arg1) {
System.out.println("Controller get and send event");
super.setChanged();
super.notifyObservers(new Object());
}
}
得到的输出是:
1 Thread started
Controller get and send event
2 Thread got event
3 We are in synchronized block!
4 Thread send event
5 Thread wait
并且线程保持锁定。预期输出:
1 Thread started
Controller get and send event
2 Thread got event
3 Thread send event
4 Thread wait
5 We are in synchronized block!
怎么了?为什么我在监视器释放之前进入同步块?PS 我有一个想法,问题是将观察者添加到 MyThread 对象,我可能会将观察者添加到 Thread 对象吗?但我怎么能做到这一点?