Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synchronizing the Methods. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synchronizing the Methods." Watch "Synchronizing the Methods." New topic
Author

Synchronizing the Methods.

Jennifer Warren
Ranch Hand

Joined: Aug 24, 2001
Posts: 53
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

Joined: Aug 24, 2001
Posts: 53
Sorry in the output it should be read as Ashfaq rather then Warren. Thax.
Jennifer
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Synchronizing the Methods.
 
Similar Threads
Doubt in Threads Synchronization
instance members, shared?
wait and notify
Explain output of this program
begin execution of a thread -- start or run?