Skip to content

Instantly share code, notes, and snippets.

@visparashar
Created February 15, 2018 10:01
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/72f5c2fa16562fbc623a6b27937f2063 to your computer and use it in GitHub Desktop.
Save visparashar/72f5c2fa16562fbc623a6b27937f2063 to your computer and use it in GitHub Desktop.
public class ProducerConsumerWaitNotifyDemo {
public static void main(String[] args) {
Processor3 p3 = new Processor3();
Thread t1 = new Thread(new Runnable(){
@Override
public void run() {
try {
p3.producer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Thread t2 = new Thread(new Runnable(){
@Override
public void run() {
try {
p3.consumer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t2.start();
}
}
class Processor3 {
private LinkedList<Integer> list = new LinkedList();
private final Integer LIMIT = 10;
Object lock = new Object();
public void producer() throws InterruptedException{
int value =0;
while(true){
synchronized (lock) {
while(list.size()==LIMIT)
{
lock.wait();
}
list.add(value++);
lock.notify();
}
}
}
public void consumer() throws InterruptedException{
Random random = new Random();
while(true){
System.out.println("Starting Consuming");
synchronized (lock) {
while(list.size()==0){
lock.wait();
}
Integer rem =list.removeFirst();
System.out.println("Removed value "+rem);
lock.notify();
}
Thread.sleep(random.nextInt(1000));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment