Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

synchronize

 
Richard Wilson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
//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?
 
Rajinder Yadav
Ranch Hand
Posts: 178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Richard Wilson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then you mean that "this " refers to thread object
defined in the anonymous class,right?
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic