Skip to content

Instantly share code, notes, and snippets.

@BT-ICD
Created April 23, 2021 14:10
Show Gist options
  • Save BT-ICD/76e662737423cf3f346bdada58a651fb to your computer and use it in GitHub Desktop.
Save BT-ICD/76e662737423cf3f346bdada58a651fb to your computer and use it in GitHub Desktop.
Example to learn about wait and notify in Thread
package ThreadWaitAndNotifyDemo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Message {
String mesg;
boolean received =false;
synchronized void readmesg(){
try{
try{
while(received){
wait();
}
}
catch(InterruptedException ex){
System.out.println("Thread interrupted while waiting");
}
InputStreamReader ins = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ins);
System.out.print("Type in a message: ");
mesg = br.readLine();
}
catch(IOException ex){
System.out.println("IO Error");
}
received=true;
notify();
}
synchronized void printmsg(){
try{
while(!received){
wait();
}
}
catch(InterruptedException ex){
System.out.println("Thread interrupted while waiting");
}
System.out.println("The received message is: " + mesg);
received=false;
notify();
}
}
package ThreadWaitAndNotifyDemo;
public class Print implements Runnable {
Message ms;
Thread th;
Print(Message ms){
this.ms = ms;
th = new Thread(this);
th.start();
}
@Override
public void run() {
ms.printmsg();
}
}
package ThreadWaitAndNotifyDemo;
public class Receive implements Runnable {
Message ms;
Thread th;
Receive(Message ms){
this.ms = ms;
th= new Thread(this);
th.start();;
}
@Override
public void run() {
ms.readmesg();
}
}
package ThreadWaitAndNotifyDemo;
/*
* Learning reference:
* Book: Programming in JAVA2
* Dr. K. Somasundaram
* */
public class ThreadDemo {
public static void main(String[] args) {
Message ms = new Message();
for (int i = 0; i < 3; i++) {
new Print(ms);
new Receive(ms);
}
}
}
@BT-ICD
Copy link
Author

BT-ICD commented Apr 23, 2021

Sample output

Type in a message: Hello
The received message is: Hello
Type in a message: How are you?
The received message is: How are you?
Type in a message: Thanks
The received message is: Thanks

@BT-ICD
Copy link
Author

BT-ICD commented Apr 23, 2021

Example on producer and consumer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment