This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question On Object Locks. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question On Object Locks." Watch "Question On Object Locks." New topic

Question On Object Locks.

Levon Escalona

Joined: Apr 07, 2006
Posts: 3
Good Day Im currently reading the K&B book and I happen to encounter this program on Chapter 9 (Threads) Here is the code:

My Question is:

On this part you class ThreadA needs to acquire the lock on Object b before it is able to enter the code right? But upon entering block it then calls method wait() on object b. Why does it need to do this? also on the run method of ThreadB there is a synchronized block where you need the lock of the class. when you called b.wait() it releases the lock on the object and waits until it gets notified. but there is only one instance of b. who is the one calling the notify method?

Asha Pathik
Ranch Hand

Joined: Feb 08, 2006
Posts: 143

class ThreadA {
public static void main(String [] args) {
ThreadB b = new ThreadB("Thread B");

synchronized(b) {
try {
System.out.println("Current Thread: "+Thread.currentThread().getName());
System.out.println("Waiting for b to complete...");
} catch (InterruptedException e) {}
System.out.println("Total is: " +;

class ThreadB extends Thread {
int total;

public ThreadB(String s)

public void run()
System.out.println("Current Thread: "+Thread.currentThread().getName()+" Started");
System.out.println("Current Thread: "+Thread.currentThread().getName()+"Inside Synchronized Block in Run");
for(int i=0;i<100;i++)
total += i;

Actually there are two threads, one is the main thread and second one is the ThreadB instance. wait() method is invoked by the main thread and since when wait() method is invoked on an object, the thread executing the code gives up its locks and goes to waiting (from K&B page 724). In this case the "main thread". The notify method is invoked by the ThreadB instance which I think you are clear about.


SCJP 1.5
Levon Escalona

Joined: Apr 07, 2006
Posts: 3
Thanks for the reply Asha it really helped me out.
Changchun Wang
Ranch Hand

Joined: Feb 15, 2006
Posts: 83
Asha Pathik is right
but now we don't know which thread will executed fristly,it up to jvm
because one thread only get locks on b and then can exeute while the other thread stay in waiting pool-

notice we dont know whih thread will get Lock frist
I agree. Here's the link:
subject: Question On Object Locks.
It's not a secret anymore!