让一个方法来锁定Java的父对象 [英] Allowing a method to lock its parent Object in Java

查看:146
本文介绍了让一个方法来锁定Java的父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在Java中的方式来获得一个方法来锁定(互斥体),它是对象?

Is there a way in Java to get a method to lock (mutex) the object which it is in?

我知道这听起来很混乱,但基本上我琬t的equivelent这个片段的C#,但在Java中。

I know this sounds confusing but basically I wan't an equivelent to this snippet of C# but in Java.

lock(this)
{
    // Some code here...
}

我一直在负责重新实现一个API用.NET编写成Java,我已经被告知要保持Java版本作为类似.NET版本以不可思议的。这不是由一个事实,即.NET版本看上去就像是从C ++版本,我不能够获得帮助转录

I've been tasked with reimplementing an API written in .Net into Java, and I've been asked to keep the Java version as similar to the .Net version as humanly possible. This isn't helped by the fact that the .Net version looked like it was transcribed from a C++ version which I don't have access to.

反正上面的行出现在C#版本,我需要的东西,做同样在Java中。

Anyway the above line appears in the C# version and I need something that does the same in Java.

推荐答案

那相当于是:

synchronized (this)
{
}

(和不,你不应该这样做通常它不是C#或Java宗教锁定在私有引用它没有别的访问您可能知道的已经,当然 - 。但我并不想离开一个答案,而不警告:)

(And no, you shouldn't generally do it in either C# or Java. Prefer locking on private references which nothing else has access to. You may be aware of that already, of course - but I didn't want to leave an answer without the warning :)

这篇关于让一个方法来锁定Java的父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆