This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes synchronization, wait and notify Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "synchronization, wait and notify" Watch "synchronization, wait and notify" New topic
Author

synchronization, wait and notify

susana miranda
Greenhorn

Joined: May 21, 2008
Posts: 9
Hello, I have a question. In the following code:

class ThreadC extends Thread{
public static void main(String [] args) {
new ThreadC().metodo1();
}

public synchronized void metodo1()
{
ThreadC b = new ThreadC();
b.start();
// synchronized(b) {
try {
System.out.println("Waiting for b to complete...");
b.wait();
} catch (InterruptedException e) {System.out.println("Error al hacer b.wait()");}
System.out.println("metodo1 terminado");
// }
}

public synchronized void run( ) {
// synchronized(this) {
System.out.println("run into ThreadB");
notify( );
System.out.println("Ya se hizo notify()");
try{
Thread.sleep(2000);
}
catch(InterruptedException e){}
System.out.println("ya se libera el lock de ThreadB");
}
// }
}

At runtime: metodo1 generates IllegalMonitorstateException, as far as I now this is because wait() must be called in a synchronized context.
1. Why isn't enough to make metodo1() synchronized?
2. Why notify() works well in run() method just by making it synchronized?

Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9189
    
    2

Hi Susana. Welcome to javaranch

1. method1 generated IllegalMonitorStateException because you are calling wait on object b

b.wait();

and method1 is synchronized on this.



2. it works in run method because you are calling notify on this reference. Since the method run is synchronized, and you call notify without using any reference variable, so it will be called on this. So the code will work as



SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
susana miranda
Greenhorn

Joined: May 21, 2008
Posts: 9
Hi Ankit, I saw my mistake. Thanks!
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: synchronization, wait and notify
 
Similar Threads
When a thread releases lock on an object?
Multithreading: How can total be nearly 5,000 even though loop is up to 100?
notify(); doesn't work?
Concept of locks and synchronization !
wait and notify problem from K&B.