package com.zybnet.so;
public class Main {
public static void main(String[] args) throws Exception{
RoundRobinBuffer buf = new RoundRobinBuffer();
Thread produce = new Thread(new Producer(buf));
Thread consume = new Thread(new consumer(buf));
produce.start();
consume.start();
produce.join();
consume.join();
System.out.println("Ok finished");
}
static class RoundRobinBuffer {
private double buff[];
private volatile int nextWrite;
private volatile int nextRead;
public RoundRobinBuffer(){
buff = new double[1000];
nextWrite = 0;
nextRead = 0;
}
public synchronized void add(double add) throws InterruptedException{
if((nextWrite + 1) % 1000 == nextRead)
wait();
buff[nextWrite] = add;
nextWrite = (nextWrite+1)%1000;
notify();
}
public synchronized double get()throws InterruptedException{
if(nextRead == nextWrite)
wait();
double temp = buff[nextRead];
nextRead = (nextRead+1)%1000;
notify();
return temp;
}
}
public static class consumer implements Runnable{
private RoundRobinBuffer consumBuff;
public consumer (RoundRobinBuffer buff){
consumBuff = buff;
}
public void run() {
for(int i = 1; i<=1000000; i++) {
try {
System.out.println("Consumer has consumed " + consumBuff.get());
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println("!!!Consumer has consumed all items!!!");
}
}
public static class Producer implements Runnable{
private RoundRobinBuffer produceBuff;
public Producer (RoundRobinBuffer buff){
produceBuff = buff;
}
public void run(){
for(int i = 1; i<=1000000; i++) {
try {
produceBuff.add(i);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
if((i % 100000) == 0)
System.out.println("Producer has produced "+ i );
}
System.out.println("Producer has produced all items.");
}
}
}