Created
February 13, 2018 09:54
-
-
Save visparashar/a5bf5984d610b30d5de91c6566ad84ca to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Producer started Producing | |
Enter Any Key to Continue | |
Resumed |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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