Saturday, March 29, 2014

Inter - Thread communication using wait(), notify() and notify all() method in Java

/*
Write a program to illustrate  inter - thread communication using wait(), notify() and notify all() method
*/

import java.io.*;
class q
{
String msg;
boolean flag;
q()
{
flag=false;
}
synchronized void get()
{
if(flag==false)
{
try
{
wait();
}//try
catch(InterruptedException e)
{

}//catch

}
flag=false;
System.out.println("Received Message"+msg);
notify();
}
synchronized void put(String x)
{
if(flag==true)
{
try
{
wait();
}
catch(InterruptedException e)
{

}//catch

}
msg = x;
flag = true;

if(msg.equalsIgnoreCase("Good Bye"))
System.exit(0);
notify();
}
}


class sender extends Thread{
q q1;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
sender(q x)
{
q1 = x;
start();
}
public void run()
{
while(true)
{
System.out.println("Enter Message ");
try
{
s = br.readLine();
q1.put(s);
}
catch(IOException e)
{

}//catch
}//while
}//run
}

class receiver extends Thread
{
q q2;
receiver(q x)
{
q2 = x;
start();

}

public void run()
{
while(true)
{
q2.get();
}
}
}

class fourteen
{
public static void main(String args[])
{
q q4 = new q();
sender s = new sender(q4);
receiver r = new receiver(q4);
}
}

7 comments:

  1. Very good brief and this post helped me alot. Say thank you I searching for your facts. Thanks for sharing with us!
    Blueprism training in marathahalli

    Blueprism training in btm

    Blueprism online training

    ReplyDelete
  2. Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in btm

    ReplyDelete
  3. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete