有人可以解释一下同步如何获取对象的锁吗?
我有一个代码,我想在其中动态获取字符串值的锁定。
例如
String a = "abc";
synchronization(a){
//some logic
}
现在我想要的是,如果我从一个请求接收到 abc 的值,而在另一个请求上我在获取上一个请求的锁定时接收到 abc 的值,则新请求应该等待值。
有人可以帮助一下它是如何工作的/我怎样才能实现这个目标?
最佳答案
Now what I want is if from an api I receive value of a abc from one request and on the other request I receive value of a as abc while obtaining lock on the previous request, the new request should wait on the basis of value.
要为此使用synchronized
,您需要确保“abc”
对象是相同的字符串对象,而不仅仅是等效字符串(出于同样的原因 you don't compare strings with ==
),通过使用 intern
。
synchronized (a.intern()) {
// ...
}
synchronized
需要相同的对象,而不仅仅是等效的对象。
关于java - 如何使用 objectId 或 hashcode 对对象进行同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55934780/