Results 1 to 2 of 2
- 11-13-2011, 12:09 PM #1
Member
- Join Date
- Nov 2011
- Posts
- 2
- Rep Power
- 0
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:
Java 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; } } }
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:
Java 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; } } }
- 11-13-2011, 06:57 PM #2
Member
- Join Date
- Nov 2011
- Posts
- 2
- Rep Power
- 0
Similar Threads
-
producer/consumer problem
By concaf in forum Threads and SynchronizationReplies: 1Last Post: 09-20-2011, 02:07 PM -
Producer-Consumer Problem
By kendel in forum Threads and SynchronizationReplies: 1Last Post: 03-04-2011, 01:09 PM -
Producer Consumer Synchronization Problem
By rushhour in forum Threads and SynchronizationReplies: 3Last Post: 11-23-2010, 07:44 PM -
Towers of Hanoi using Producer/Consumer Pattern
By dooey in forum New To JavaReplies: 0Last Post: 09-08-2009, 12:45 PM -
Implementation of the Producer/Consumer problem in Java
By Java Tip in forum java.langReplies: 0Last Post: 04-09-2008, 06:41 PM
Bookmarks