Docsity

Producer Consumer Test-Advanced Computer Programming-Code, Lecture notes of Advanced Computer Programming

Toggle sidebar
bg1
public class ProducerConsumerTest {
public static void main(String[] args) {
Plate c = new Plate();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class Plate {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
} catch (InterruptedException e) { }
}
available = false;
notifyAll();
return contents;
}
Docsity.com
pf3
pf4

Partial preview of the text

Download Producer Consumer Test-Advanced Computer Programming-Code and more Lecture notes Advanced Computer Programming in PDF only on Docsity!

public class ProducerConsumerTest { public static void main(String[] args) { Plate c = new Plate(); Producer p1 = new Producer(c, 1); Consumer c1 = new Consumer(c, 1); p1.start(); c1.start(); } } class Plate { private int contents; private boolean available = false; public synchronized int get() { while (available == false) { try { wait(); } catch (InterruptedException e) { } } available = false; notifyAll(); return contents; }

public synchronized void put(int value) { while (available == true) { try { wait(); } catch (InterruptedException e) { } } contents = value; available = true; notifyAll(); } } class Consumer extends Thread { private Plate Plate; private int number; public Consumer(Plate c, int number) { Plate = c; this.number = number; } public void run() { int value = 0;

sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } } }