Jump to content

Concurrency: Producer-Consumer Problem

- - - - -

  • Please log in to reply
No replies to this topic

#1
Corwin

Corwin

    Newbie

  • Members
  • PipPip
  • 12 posts
This is a basic implementation of the producer-consumer problem in Java using ArrayBlockingQueue that I did some time ago (my original post with a bit more details).


/* Driver.java*/

import java.util.concurrent.ArrayBlockingQueue;


class Driver {

    public static void main (String[] args) {

        ArrayBlockingQueue<Integer> q = new ArrayBlockingQueue<Integer>(5);


        Thread p = new Thread(new Producer(q));

        Thread c = new Thread(new Consumer(q));


        p.start();

        c.start();


        try {

            p.join();

            c.join();

        } catch (java.lang.InterruptedException e) {

            System.err.println(e);

        }

    }

}



/* Producer.java */

import java.util.concurrent.ArrayBlockingQueue;


public class Producer implements Runnable {

    private ArrayBlockingQueue<Integer> q;


    Producer(ArrayBlockingQueue<Integer> q) {

        this.q = q;

    }


    public void run() {

        /* Come up with the next number and "put" it in the queue*/

        for(int i=0; i<10; i++) {

            try {

                q.put(56);

            } catch (java.lang.InterruptedException e) {

                System.err.println(e);

            }

        }

    }

}



/* Consumer.java */

import java.util.concurrent.ArrayBlockingQueue;


public class Consumer implements Runnable {

    private ArrayBlockingQueue<Integer> q;


    Consumer(ArrayBlockingQueue<Integer> q) {

        this.q = q;

    }


    public void run() {

        int n;

        for(int i=0; i<20; i++) {

            try {

                n = q.take();

                /* Use n */

                System.out.println(n);

            } catch (java.lang.InterruptedException e) {

                System.err.println(e);

            }

        }

    }

}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users