Skip to content

Instantly share code, notes, and snippets.

@visparashar
Created February 13, 2018 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save visparashar/a5bf5984d610b30d5de91c6566ad84ca to your computer and use it in GitHub Desktop.
Save visparashar/a5bf5984d610b30d5de91c6566ad84ca to your computer and use it in GitHub Desktop.
Producer started Producing
Enter Any Key to Continue
Resumed
import java.util.Scanner;
public class WaitNotifyDemo {
public static void main(String[] args) {
Processor2 process = new Processor2();
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
try {
process.producer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
try {
process.consumer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
class Processor2{
public void producer() throws InterruptedException {
synchronized (this) {
System.out.println("Producer started Producing");
wait();// we should always use wait in while() loop not in if block
System.out.println("Resumed");
}
}
public void consumer() throws InterruptedException{
Thread.sleep(1000);
Scanner sc = new Scanner(System.in);
synchronized (this) {
System.out.println("Enter Any Key to Continue");
sc.nextLine();
notify();
//notifyAll() // if there are more than 2 threads are in program we will use notifyAll()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment