gpt4 book ai didi

java - 观察者,可观察和可运行。为什么同步块(synchronized block)丢失监视器?

转载 作者:行者123 更新时间:2023-11-30 09:24:17 24 4
gpt4 key购买 nike

我正在尝试将类用作 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!

怎么了?为什么我在监视器释放之前进入同步块(synchronized block)?附言我有一个想法,问题是将观察者添加到 MyThread 对象,我可以将观察者添加到 Thread 对象吗?但是我该怎么做呢?

最佳答案

好吧,我认为您遇到的主要问题是 synchronized 关键字类似于可重入锁 (http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html)。

这意味着,当您在 MyThreadrun 方法中时,您正在通知 Controller。这个然后调用你的 MyThreadupdate 进入 synchronized block (因为它是可重入的)并完成这个方法。之后,Controller.update 方法返回并且您的 MyThread.run 方法的其余部分继续,因此卡在 this.wait() 上。

关于java - 观察者,可观察和可运行。为什么同步块(synchronized block)丢失监视器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15766056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com