简体   繁体   English

Java线程教程

[英]Java Threading Tutorial

I'm looking through the Java concurrency tutorials to get an idea of how this works in Java and had a question regarding the "MsLunch" example @ http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html 我正在浏览Java并发教程,以了解它在Java中的工作方式,并对“ MsLunch”示例@ http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync有疑问。 HTML

I'm trying to understand in the MsLunch example, the difference between coding it as shown, and using 2 synchronized methods. 我试图在MsLunch示例中理解,如图所示进行编码与使用2种同步方法之间的区别。

From what I can understand, using the synchronized keyword on methods relies on an instrinic lock associated with that methods object. 从我能理解,使用synchronized的方法关键字依赖于与该方法的对象相关联的instrinic锁。 So if a class has two synchronized methods a() and b() , a() and b() cannot be called concurrently on the same object. 因此,如果一个class具有两个synchronized方法a()b() ,则不能在同一对象上同时调用a()b()

But coding a() and b() as shown in the MsLunch class allows both methods to be called on the same object at the same time. 但是,如MsLunch类中所示对a()b()编码,则可以同时在同一对象上调用这两种方法。

Is my understanding correct? 我的理解正确吗?

MsLunch example uses synchronized blocks with different object instances to lock. MsLunch示例使用具有不同对象实例的synchronized块进行锁定。 Hence both inc1() and inc2() can run concurrently. 因此, inc1()inc2()都可以同时运行。

If it were synchronized methods, in that case this will be used to lock, methods inc1() and inc2() would be executed serially. 如果它被同步方法,在这种情况下this将被用于锁定,方法inc1()inc2()将被串行执行。

http://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html中, MSLunch具有Sync块,而不是在两个不同的锁上都具有同步方法,因此,是的,两个线程将不会相互阻塞,并且能够同时访问方法。

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

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