wood burning stoves 2.0*
The moose likes Threads and Synchronization and the fly likes To which of the following can we apply the synchronized keyword Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "To which of the following can we apply the synchronized keyword" Watch "To which of the following can we apply the synchronized keyword" New topic
Author

To which of the following can we apply the synchronized keyword

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
To which of the following can we apply the synchronized keyword
Options :
a . A top level class
b . A static member variable
c . A static method
d . An instance variable
e . An instance method
I think the answer is c, d, e,
You can apply the „synchronized“ to an instance method
class Blair2 extends Thread {
public synchronized void run() {

You can apply the „synchronized“ to an instance variable like „t“:
class Blair extends Thread {
public void run() {
Thread t = Thread.currentThread();
synchronized (t) {

Appreciate your oppinion.
Thanks.
Cindy Glass
"The Hood"
Sheriff

Joined: Sep 29, 2000
Posts: 8521
Moving to Threads.


"JavaRanch, where the deer and the Certified play" - David O'Meara
Ken Krebs
Ranch Hand

Joined: Nov 27, 2002
Posts: 451
You cannot apply synchronized to a variable. You can only apply it to a method or a code block. If you apply it to a static method, any thread must acquire the class's object lock before it may continue executing the synchronized code. If you apply it to an instance method, any thread must acquire the instance's object lock before it may continue executing the synchronized code. If you apply it to a block of code, any thread must acquire the specified object's lock to continue executing the synchronized code.
Ken Krebs
"The way of the threaded warrior is resolute acceptance of thread death." --- Ken Krebs with apologies to Miyamoto Musashi


kktec<br />SCJP, SCWCD, SCJD<br />"What we observe is not nature itself, but nature exposed to our method of questioning." - Werner Heisenberg
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2835
    
  11

This may just be a semantic dispute, but when you synchronize a block of code, you do apply "synchronized" to an object. Of course, it's the block of code you are synchronizing, not the object itself. Synchronizing an object has no meaning.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: To which of the following can we apply the synchronized keyword
 
Similar Threads
Inner Class - Initialization Sequence
Thread with synchronized run() method and sleep()
Synchronized block K&B problem
Question on thread q.2 pg 734
Thread with synchronized run() method and sleep()