aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronize Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "synchronize" Watch "synchronize" New topic
Author

synchronize

Richard Wilson
Ranch Hand

Joined: Jan 12, 2002
Posts: 57
//if a thread defined like this in a class
new Thread() {
public void run(){
synchronized(this) {
System.out.println("Reach Sync");
}
}
}.start();
What does the this refer to?
When a thread goes into the sync block,whose lock
the thread will acquire?Thread Object or Enclosing Class Object?


Richard Wilson
Rajinder Yadav
Ranch Hand

Joined: Jan 18, 2002
Posts: 178
The "this" operator refers to the object itself, take a looks at this code, and note how "this.i" refers to the object's variable i which is use to distinguish between the passed var i within the ctor!

A call to synchronized(this) will lock on the object that the call in made from, any other threads that try to aquire a lock on this object will block until the synchronized block completes!
[ February 18, 2002: Message edited by: Rajinder Yadav ]

<a href="http://www.rajindery.com" target="_blank" rel="nofollow">Rajinder Yadav</a><p>Each problem that I solved became a rule which served afterwards to solve other problems. --Rene Descartes
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Originally posted by Richard Wilson:
//if a thread defined like this in a class
new Thread() {
public void run(){
synchronized(this) {
System.out.println("Reach Sync");
}
}
}.start();

This code is equivalent to:


Rob
SCJP 1.4
Richard Wilson
Ranch Hand

Joined: Jan 12, 2002
Posts: 57
Then you mean that "this " refers to thread object
defined in the anonymous class,right?
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
Right.
an unqualified this always refers the innermost object in which it is encountered.
You can also qualify the this with the name of an enclosing class, and it will evaluate to that object.
For example:

[ February 18, 2002: Message edited by: Rob Ross ]
Murgan Sub
Greenhorn

Joined: Feb 06, 2002
Posts: 22
public class Foo {
int i=5;
public void aMethod() {
System.out.println(this.i);
Object o = new Object(){
int i = 7;
public void aMethod(){
System.out.println(this.i); System.out.println(Foo.this.i);
}
}; // Semicolon required here
}
}
Just Corrected the syntax
 
wood burning stoves
 
subject: synchronize