To which of the following can we apply the synchronized keyword
Thomas Markl
Ranch Hand
Joined: Mar 08, 2001
Posts: 192
posted
0
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
posted
0
Moving to Threads.
"JavaRanch, where the deer and the Certified play" - David O'Meara
Ken Krebs
Ranch Hand
Joined: Nov 27, 2002
Posts: 451
posted
0
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
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.