Created
February 15, 2018 10:01
-
-
Save visparashar/72f5c2fa16562fbc623a6b27937f2063 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
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