哪个线程会获得锁?
假设我们有多处理器机器和多线程应用程序。如果两个线程可以访问同步方法并且同时执行,哪个线程将获得锁? 或者会发生什么?
谢谢
suppose we have multi processor machine and multi threaded application. If two threads have access to a synchronized method and they got executed at the same time which thread will gets the lock?
or what will happen?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该行为将是非确定性(即,任一线程都可以获得锁),并且它可能因执行而异。这是因为它取决于特定的 JVM 实现以及线程的特定调度。
根据这篇文章,JVM 规范对公平性没有任何限制:
也就是说,除非您仔细同步程序,否则理论上一个线程可能会被调度程序饿死。
The behaviour will be non-deterministic (that is, either thread may get the lock), and it may vary from execution to execution. This is because it depends on the specific JVM implementation, and the particular scheduling of your threads.
According to this article the JVM specification puts no restrictions on fairness:
That is, unless you carefully synchronize your program, one thread may theoretically get starved by the scheduler.
关键是不存在“同时”这样的事情。两者之一将获得锁,但你无法知道是哪一个。
不存在“同时”这样的事情,因为从广义上讲,锁是一次独占地选择和执行一个线程的东西。
这自然是在一次可以执行一条指令的纯单处理器系统中完成的。在多处理器系统上,通常有一些硬件设备“锁定”处理器以防止它们同时执行。
The point is that there is no such thing as "at the same time". One of the two will get the lock, but you have no way to know which one.
There is no such thing "at at the same time" because, liberally speaking, a lock is something that chooses and executes the threads one at a time exclusively.
This is naturally accomplished in a pure monoprocessor system that can execute one instruction at a time. On multiprocessor systems usually there is some hardware device that "locks" the processors to prevent them from executing at the same time.