简体   繁体   English

当线程移出对象的监视器时,这意味着什么?

[英]What does it mean when a thread moves out of an object's monitor?

我仅想知道的是,当线程退出锁时,这是否意味着它“结束”,或者只是它已经完成了使用该函数或代码的代码,而该函数或代码使用了该特定线程所在的监视器的对象?

Just that it has finished using that function or code which employed the use of the object. 只是它已经完成了使用该对象使用的功能或代码。 Such pieces of code are commonly known as critical section (s). 这样的代码通常称为关键部分

For your general understanding: methods run on threads. 大致了解一下:方法在线程上运行。 So it is possible that one method is being executed by multiple threads at the same time. 因此,一个方法可能同时由多个线程执行。

Imagine you want to make sure that a method, or part of it, can only be executed by one thread at a time. 假设您要确保某个方法或其一部分只能一次由一个线程执行。 This is called a critical section. 这称为关键部分。

A critical section in Java can be protected by a lock: implicitly via synchronized or explicitly via java.util.concurrent.locks . Java的关键部分可以通过锁来保护:通过同步隐式地或通过java.util.concurrent.locks显式地。

Only one thread at a time can acquire the lock and entering the critical section requires that the lock be acquired first. 一次只有一个线程可以获取锁,进入关键部分要求首先获取锁。 At the end of the critical section the lock is released and the thread continues running but now without holding that lock. 在关键部分的末尾,锁被释放,线程继续运行,但是现在不持有该锁。

A thread encountering a lock held by another thread (not necessarily for the same critical section) cannot proceed at that point and must wait. 遇到另一个线程(不一定是同一关键部分)持有的锁的线程无法在该点继续执行,必须等待。 The thread, and other threads waiting on the same lock, will be notified when they can retry to acquire the lock. 当线程和其他等待同一锁的线程可以重试获取锁时,将收到通知。 Again, only one thread will win and the process repeats (unless you have a deadlock for example). 同样,只有一个线程将获胜,并且该过程将重复(例如,除非出现死锁 )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM