简体   繁体   English

Java的“同步”和C#的“锁定”之间有什么区别吗?

[英]Are there any differences between Java's “synchronized” and C#'s “lock”?

这两个关键字是否具有完全相同的效果,或者我应该注意哪些?

根据这个站点: http//en.csharp-online.net/CSharp_FAQ_What_is_the_difference_between_CSharp_lock_and_Java_synchronized ,C# lock和Java synchronized代码块“语义相同”,而对于方法,Java使用synchronized同时C#使用属性: [MethodImpl(MethodImplOptions.Synchronized)]

One interesting difference not covered in the link posted by Keeg: as far as I'm aware, there's no equivalent method calls in Java for .NET's Monitor.Enter and Monitor.Exit , which the C# lock statement boils down to. Keeg发布的链接中没有涉及的一个有趣的区别:据我所知,在Java的Monitor.EnterMonitor.Exit中没有等效的Java 方法调用,C# lock语句归结为。 That means you can't do the equivalent of Monitor.TryEnter either - although of course the java.util.concurrent.locks package (as of 1.5) has a variety of locks which have more features available. 这意味着你不能做相当于Monitor.TryEnter的工作 - 当然java.util.concurrent.locks包(从1.5开始)有各种各样的锁具有更多的功能。

I java you don't have to worry about locking public types that you own. 我java你不必担心锁定你拥有的公共类型。

In .NET, you have to 在.NET中,你必须这样做

Updated: this is for types that you own. 更新:这适用于您拥有的类型。 Locking on public types that you don't own is bad in any language :) 锁定你不拥有的公共类型在任何语言中都是糟糕的:)

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

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