Я пытаюсь использовать класс как Наблюдатель и Наблюдаемый. Этот класс будет запущен как поток. В методе 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());
}
}
Getted выход:
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!
Что случилось? Почему я пришел в синхронизированный блок до того, как вышел монитор? P.S. У меня есть идея, что проблема заключается в добавлении наблюдателя в объект MyThread, может быть, я добавлю наблюдателя в объект Thread? Но как я мог это сделать?
Кажется, нет никакого другого потока, чтобы уведомить нить ожидания – prasanth
Ваш thread застрял здесь 'this.wait();' – prasanth