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

Synchornized inside run

 
M Rama
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Continuing with my Thread vs Runnable doubts, in the following code:



Here, which object is locked for the synchronized. Is it Thread object or Runnable?

The output prints:

this is the object of thread1.SynchInRunnable@119c082



which doesn't tell me a whole lot
 
vinuharan haran
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
i just called the holdsLock method in ur code.


The output is true.

If u type cast this(current object) to Thread it will give compiler error.
so it holds the runnable object lock.
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's another way of knowing that "this" is a Runnable, not a Thread:

The "this" object always refers to an instance of the enclosing class, which is SynchInRunnable in this case. Since SynchInRunnable is a Runnable, not a Thread, "this" must be a Runnable.

To find out what class an object is an instance of, you can do this:


The output is:
this is an instance of SynchInRunnable
[ April 14, 2005: Message edited by: Joe Sanowitz ]
 
Joe Sondow
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Getting a little off topic, but if you really want to test whether something is a subclass or implementer of something else, you can run reflection code like this:


[ April 14, 2005: Message edited by: Joe Sanowitz ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic