aspose file tools*
The moose likes Threads and Synchronization and the fly likes Producer consumer thread problem. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Threads and Synchronization
Bookmark "Producer consumer thread problem." Watch "Producer consumer thread problem." New topic
Author

Producer consumer thread problem.

Tony Evans
Ranch Hand

Joined: Jun 29, 2002
Posts: 556
Run I run my application both threads block. The consumer blocks waiting to be notified. The Producer every time it carrys out an action calls notifyAll(), this does not wake up the consumer thread, I guess that even though it has called notifyAll it still has the lock. It only releases the lock on a wait.



When it can no longer produce it goes into a wait state so both threads are waiting.

synchronized void produce(){
Date message;
while(true){
System.out.println("Producer produce "+buffer.getBufferSize());
SleepUtilities.nap();
message = new Date();
try {
if(buffer.getBufferSize() < buffer.getBufferLength()){
buffer.insert(message);
// As well as calling notifyAll what else can I do here
notifyAll();
}else{
wait();
}

}catch(InterruptedException e){
System.out.println("Producer "+e);
}
}
}

synchronized public void consume(){
Date message;
while(true) {
System.out.println("Consumer consume "+buffer.getBufferSize());
SleepUtilities.nap();
try {
if(buffer.getBufferSize() > 0) {
message = (Date)buffer.remove();
System.out.println("Consumer consume call notify");
notifyAll();

} else {
System.out.println("Consumer consume Enter wait state");
wait();
}
}catch(InterruptedException e){
System.out.println("Consumer "+e);
}
}
}

Thanks for any help
Tony Evans
Ranch Hand

Joined: Jun 29, 2002
Posts: 556
Fixed to use synchronized wait and notify it must be on the same object. Instead of the producer and consumer it should of been on my boundedBuffer insert remove methods.

public synchronized void insert(Object item) throws InterruptedException{
if(nextFreePostion > BUFFER_SIZE){
wait();
}
System.out.println("Insert "+item+" into Buffer");
buffer[nextFreePostion] = item;
nextFreePostion = (nextFreePostion+1) %BUFFER_SIZE;
bufferSize++;
notifyAll();
}

public synchronized Object remove() throws InterruptedException{
if(nextFullPostion == 0){
wait();
}
Object item = buffer[nextFullPostion];
System.out.println("Remove "+item+" from Buffer");
nextFullPostion = (nextFullPostion+1) %BUFFER_SIZE;
bufferSize--;
notifyAll();
return item;
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Producer consumer thread problem.
 
Similar Threads
Threads
call to wait and and subsequent call to notify is not resuming the work
How to request monitor info on/from a locked object
Thread question
Important, about threads