• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

thread doubt

 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


options:

a. The number printed is greater than or equal to 0
b. The synchronized block inside the run method is not necessary
c. This program runs to completion after the elapsed time is printed
d. Compile-time error
e. Run-time error
f. None of the above

answer::-a

Here instance variable is boolean. How can synchronized block take boolean lock ?
 
Amit M Tank
Ranch Hand
Posts: 257
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The sync block doesn't take boolean. It takes the "this" which is the current instance of the Thread. You can take locks only on objects not primitive data types.

Amit Tank
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



Reason why answer is 'A', it seems it is clear to you. Infinitely wait is
done, no code is there that sets done=true.




Thanks,
 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Chandra,
I am little confuse about (this) means current instance. And here current instance is boolean. So how synchronized can take lock of (this)?
Can you explained?
Thanks.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by dolly shah:
Hi Chandra,
I am little confuse about (this) means current instance. And here current instance is boolean. So how synchronized can take lock of (this)?
Can you explained?
Thanks.


Nay Dolly, boolean is not current instance.
See the following points regarding your class:

1- "A" is a class, every instance of your class 'A' will contain a variable
done. "done" is an instance variable.
2- "a1" is a thread object.
3- You are simply acquiring lock of the thread object 'A' before entering
to the sync code.
4- Any code that writes "this" inside the code of your class (non-static),
it will refer to current object. Suppose you call a1.method() and
inside method() you say "this", it means you are referring to the object
using the ref variable you have called the method.

Note: Try to implement the full code, that demonstrate the use of "done",
to exit from the waiting loop. It may help you to understand the things
in much better way;

Thanks,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic