Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synchronizing the Methods.

 
Jennifer Warren
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic