coder005
coder005

Reputation: 79

Producer consumer using blockingqueue

I have started learning threads and tried Producer consumer problem in Java using concurrent package introduced in JDK 5.0 I have written the following code:

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class Producer implements Runnable {
    private final BlockingQueue<Integer> objqueue;

    Producer(BlockingQueue<Integer> obj) {
    objqueue = obj;
    }

    @Override
    public void run() {
    int i = 0;
    while (i < 10) {
        try {
            System.out.println("Put : " + i);
            objqueue.put(i);
        } catch (InterruptedException e) {
        }
        i++;
    }
    }
}

class Consumer implements Runnable {
private final BlockingQueue<Integer> objqueue;

Consumer(BlockingQueue<Integer> obj) {
    objqueue = obj;
}

@Override
public void run() {
    while (true) {
        try {
            System.out.println("Got : " + objqueue.take());
        } catch (InterruptedException e) {
        }
    }
}

}

public class PCMain {

public static void main(String[] args) {
    // create shared object
    BlockingQueue<Integer> obj = new LinkedBlockingQueue<Integer>();

    Thread prod = new Thread(new Producer(obj));
    Thread cons = new Thread(new Consumer(obj));

    prod.start();
    cons.start();
}

}

The program is not terminating when the producer has produced up to 9 and consumer consumed up to 9. Should I remove the while loop which is true forever in Consumer.

How can I make it for more than one Producer and one Consumer? Thanks.

Upvotes: 0

Views: 320

Answers (3)

John Vint
John Vint

Reputation: 40256

Well you have two threads, one should stop once i == 10. The other thread is in an infinite loop though. You need to signal to the consuming thread that the application should end. Look at the Poison Pill as a way of telling the second thread to stop.

The program itself won't stop until that consuming thread completed.

Upvotes: 1

markspace
markspace

Reputation: 11030

I think the easiest way to "fix" your code is to make the consumer a daemon thread.

Thread prod = new Thread(new Producer(obj));
Thread cons = new Thread(new Consumer(obj));

cons.setDaemon( true );
prod.start();
cons.start();

This really isn't a general solution, but a good trick to keep in mind when it's inconvenient to signal a thread to stop.

Upvotes: 0

ravi singh
ravi singh

Reputation: 1

Removing while loop will cause consumer will consume only 1 object given by producer.

Better to go Excecuter framework. It is having Thread Factory and Thread Pool.You can use to implement the same.

Upvotes: 0

Related Questions