Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Synchronizing the Methods.

 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Felas,
Below find a program which is bugging me a little.
class MyMsg{
private String Msg = "";
static boolean flag = false;
synchronized void setMsg(String s){
Msg = s;
flag = true;
System.out.println(Thread.currentThread().getName());
notifyAll();
}
synchronized String getMsg(){
while(true){
if(flag == false){
try{
wait();
}
catch(InterruptedException e){
System.out.println(e);
}
}
flag = false;
return Msg;
}
}
}
class MyThread1 extends Thread{
MyMsg a;
String Msg;
MyThread1(MyMsga, String Msg){
this.a = a;
this.Msg = Msg;
}
public void run(){
System.out.println(a.getMsg() +" " +this.getName() );
a.setMsg(Msg);
}
}
class MyThread2 extends Thread{
MyMsg a;
String Msg;
MyThread2(MyMsga, String Msg){
this.a = a;
this.Msg = Msg;
}
public void run(){
a.setMsg(Msg);
System.out.println(a.getMsg() +" " +this.getName() );
}
}
class MyMsgDemo{
public static void main (String args[]){
MyMsg a = new MyMsg();
MyThread1 t1 = new MyThread1(a, "Ashir");
MyThread2 t2 = new MyThread2(a, "Ashfaq");
t1.start();
t2.start();
}
}
The Output is :
Thread1
Warren Thread1
Warren Thread0
Thread0
The method is not working upto my calculation. Since when ever the getMsg is executed it sets the flag false then how come the Msg is retrieved twice with out being set again.
Please explain why this output.
Thanks and regards.
Jennifer Warren.
 
Jennifer Warren
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry in the output it should be read as Ashfaq rather then Warren. Thax.
Jennifer
 
I think he's gonna try to grab my monkey. Do we have a monkey outfit for this tiny ad?
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic