简体   繁体   中英

Difference between wait() and this.wait()

I got a java code snippet here which got me wondering what the difference between the calls wait() and this.wait() is.

Lets say you have a class with a method to take a resource and that is synchronized. Normally I would write wait() in the while loop if the resource is not available but what happens if you call this.wait() ? Whose monitor will be blocked? The monitor of the class object or the resource? And to which object does the statement "this" refer to?

Sorry for asking this super basic question but I couldn't find any help through google.

Thanks for helping !

There isn't any difference in that case, this.wait() and wait() will call the same method.

Take a look at the oracle docs about the this keyword in Java.

From the documentation:

Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this .

this关键字引用了类的当前实例,并且由于从对象本身调用wait()已经引用了当前实例的函数,因此在你的情况下wait()this.wait()之间没有区别。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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