Vous êtes sur la page 1sur 2

public class Test {

private static int count;


private static int buffer[];
private static int data = 1;
private static Object lock = new Object();

public static class Producer {


public void produce() {
synchronized (lock) {
if (isFull(buffer)) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println("Producer has produced : " +
data);
buffer[count++] = data++;
lock.notify();
System.out.println("Producer has sent
notification.");
}
}
}
}

public static class Consumer {


public void consume() {
synchronized (lock) {
if (isEmpty(buffer)) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println("Consumer consumed value : " +
buffer[--count]);
buffer[count] = 0;
lock.notify();
System.out.println("Consumer has sent
notification.");
}
}
}
}

public static boolean isFull(int[] buffer) {


return count == buffer.length;
}

public static boolean isEmpty(int buffer[]) {


return count == 0;
}

public static void main(String[] args) throws InterruptedException {


count = 0;
buffer = new int[10];
Producer p = new Producer();
Consumer c = new Consumer();

Thread producer = new Thread() {

@Override
public void run() {
for (int i = 1; i <= 20; i++) {
System.out.println("producer iteration : " + i);
p.produce();

}
}
};

Thread consumer = new Thread() {

@Override
public void run() {
for (int i = 1; i <= 20; i++) {
System.out.println("consumer iteration : " + i);
c.consume();
}
}
};

producer.start();
consumer.start();

producer.join();
consumer.join();

System.out.println("Data in buffer : " + count);


}
}