哪个线程会获得锁?

发布于 2024-09-27 15:28:07 字数 77 浏览 4 评论 0原文

假设我们有多处理器机器和多线程应用程序。如果两个线程可以访问同步方法并且同时执行,哪个线程将获得锁? 或者会发生什么?

谢谢

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倚栏听风 2024-10-04 15:28:07

该行为将是非确定性(即,任一线程都可以获得锁),并且它可能因执行而异。这是因为它取决于特定的 JVM 实现以及线程的特定调度。

根据这篇文章,JVM 规范对公平性没有任何限制:

公平
Java 内存模型没有为线程或抢占式多线程指定任何公平性要求。一个线程可以拒绝将 CPU 交给另一个线程,从而使系统陷入死锁。对其他线程的公平规则由各个 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:

Fairness
The Java memory model does not specify any fairness requirement for threads or preemptive multi-threading. A thread can refuse to surrender the CPU to another thread and throw the system into deadlock. The rules for fairness to other threads are defined by the individual JVM implementations.

That is, unless you carefully synchronize your program, one thread may theoretically get starved by the scheduler.

南汐寒笙箫 2024-10-04 15:28:07

关键是不存在“同时”这样的事情。两者之一将获得锁,但你无法知道是哪一个。

不存在“同时”这样的事情,因为从广义上讲,锁是一次独占地选择和执行一个线程的东西。

这自然是在一次可以执行一条指令的纯单处理器系统中完成的。在多处理器系统上,通常有一些硬件设备“锁定”处理器以防止它们同时执行。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文