Consumer/Producer with random numbers
Hi, i am stuck with a threads problem and I would greatly appreciate any help from you guys:
I have to create two threads, one which produces random numbers and a second one which prints them. Between the threads should be a fixed-size buffer (if the buffer is empty, the consumer has to wait, if the buffer is full, the producer has to wait). This should be implemented twice:
a) system-programmer's view: use wait(), notifyAll(), synchronized{} (use an array for the buffer)
b) application-programmer's view: use suitable classes from the Java library to implement the buffer
As for a), I tried to write the producer somehow like this, but it seems there is something wrong with it:
Code:
public class Producer implements Runnable {
public void run(){
int size=10;
int i;
double numbers[] = new double[size];
for (i=0; i<size; i++) {
numbers[i] = Math.random()*99 + 1;
}
}
}
Also, I am stuck with the buffer and the consumer. How do I use the numbers from the producer? I am really lost ... :(doh):
As for b), I know that BlockingQueue would be appropriate. I tried to write the producer like this, but again, it doesn't seem right:
Code:
import java.util.*;
import java.util.concurrent.BlockingQueue;
class Producer2 implements Runnable {
private final BlockingQueue queue;
Producer2 (BlockingQueue q) { queue = q; }
public void run() {
try {
while(true) { queue.put(produce()); }
}
catch (InterruptedException ex) { System.out.println("Something went wrong!"); }
}
Object produce() {
int size=100;
int i;
double numbers[] = new double[size];
for (i=0; i<size; i++) {
numbers[i] = Math.random()*99 + 1;
}
}
}
I am seriously lost at this point. Any help or hint would be greatly appreciated. Thanks in advance!
Re: Consumer/Producer with random numbers
nevermind, I was able to figure it out myself :8):