• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

synchronization, wait and notify

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?

 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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

 
susana miranda
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Ankit, I saw my mistake. Thanks!
 
That new kid is a freak. Show him this tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic