Object上的Java同步.为什么不会出现这种僵局?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Object上的Java同步.为什么不会出现这种僵局?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1865字,纯文字阅读大概需要3分钟。
内容图文
![Object上的Java同步.为什么不会出现这种僵局?](/upload/InfoBanner/zyjiaocheng/796/b507c62138634268a699893d86f9972c.jpg)
下面的构造工作并做我想要的,但我想理解为什么它不会死锁.
下面的示例确保用户在继续执行之前(在EDT上)弹出的JOptionPane框上单击了yes或no.
package waitexample;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class WaitExample {
public static void main(String[] args) throws InterruptedException {
System.out.println("starting");
Object myWaiter = new Object();
SwingUtilities.invokeLater(() -> {
System.out.println("invoked");
JOptionPane.showConfirmDialog(null, "Message", "Title", JOptionPane.YES_NO_OPTION);
synchronized (myWaiter) {
System.out.println("calling notify");
myWaiter.notify();
System.out.println("notified");
}
});
synchronized (myWaiter) {
System.out.println("waiting");
myWaiter.wait();
System.out.println("done waiting");
}
System.out.println("ending main()");
}
}
但看起来我正在使用不同的线程同时输入synchronized(myWaiter)块,给出以下输出:
starting
waiting
invoked
calling notify
notified
done waiting
ending main()
为什么不会出现这种僵局?
解决方法:
引用wait的文档,
The thread releases ownership of this monitor and waits until another
thread notifies threads waiting on this object’s monitor to wake up
either through a call to the notify method or the notifyAll method.
The thread then waits until it can re-obtain ownership of the monitor
and resumes execution.
这解释了最直线
starting
waiting
invoked <- could have appeared before or after waiting
并引用notify的文档,
The awakened thread will not be able to proceed until the current
thread relinquishes the lock on this object. The awakened thread will
compete in the usual manner with any other threads that might be
actively competing to synchronize on this object; for example, the
awakened thread enjoys no reliable privilege or disadvantage in being
the next thread to lock this object.
这解释了
calling notify
notified
此时EDT线程放弃同步块并释放锁定,接下来的行如下:
done waiting
ending main()
内容总结
以上是互联网集市为您收集整理的Object上的Java同步.为什么不会出现这种僵局?全部内容,希望文章能够帮你解决Object上的Java同步.为什么不会出现这种僵局?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。