Using Wait and Notify
public class ProducerConsumer {
LinkedList<Integer> list = new LinkedList<>();
private static final int limit = 10;
private Object lock = new Object();
public void produce() throws InterruptedException {
int value = 0;
while (true) {
synchronized (lock) {
while (list.size() == limit) {
System.out.println("List is full, so Produce thread is waiting..");
lock.wait();
}
list.add(value++);
System.out.println("Producer thread is notify..");
lock.notifyAll();
}
}
}
public void consume() throws InterruptedException {
while (true) {
synchronized (lock) {
while (list.size() == 0) {
System.out.println("List is empty, so Consumer thread is waiting..");
lock.wait();
}
int val = list.remove(0);
System.out.println("Consumer thread notify..");
lock.notifyAll();
}
}
}
public static void main(String a[]) {
final ProducerConsumer producerConsumer = new ProducerConsumer();
Thread producerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
producerConsumer.produce();
} catch (Exception e) {
e.printStackTrace();
}
}
});
Thread consumerThread = new Thread(new Runnable() {
@Override
public void run() {
try {
producerConsumer.consume();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
producerThread.start();
consumerThread.start();
}
}
Using BlockingQueue
public class ProducerConsumerWithBlockingQueue {
private final int LIMIT = 10;
private BlockingQueue<Integer> blockingQueue = new LinkedBlockingDeque<Integer>();
public void producer() throws InterruptedException{
int val = 0;
while (true) {
blockingQueue.put(val++);
}
}
public void consumer() throws InterruptedException {
while(true) {
int val = blockingQueue.take();
}
}
}
No comments:
Post a Comment