Java Multithreading: Producer-Consumer (Video Tutorial Part 7)

A tutorial on how to implement the producer-consumer pattern in Java using the ArrayBlockingQueue Java class. Producer-Consumer is the situation where one or more threads are producing data items and adding them to a shared data store of some kind while one or more other threads process those items, removing them from the data store.

After starting the video, click the maximise button to make it fullscreen so you can see the code!

Code For This Tutorial

import java.util.Random;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;


public class App {
	
	private static BlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(10);
	
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				try {
					producer();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				try {
					consumer();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		t1.start();
		t2.start();
		
		t1.join();
		t2.join();
	}
	
	private static void producer() throws InterruptedException {
		Random random = new Random();
		
		while(true) {
			queue.put(random.nextInt(100));
		}
	}
	
	private static void consumer() throws InterruptedException {
		Random random = new Random();
		
		while(true) {
			Thread.sleep(100);
			
			if(random.nextInt(10) == 0) {
				Integer value = queue.take();
				
				System.out.println("Taken value: " + value + "; Queue size is: " + queue.size());
			}
		}
	}
}
Taken value: 59; Queue size is: 10
Taken value: 40; Queue size is: 10
Taken value: 74; Queue size is: 9
Taken value: 40; Queue size is: 9
Taken value: 88; Queue size is: 9
Taken value: 74; Queue size is: 9
Taken value: 96; Queue size is: 9
Taken value: 88; Queue size is: 10
Taken value: 34; Queue size is: 10
Taken value: 81; Queue size is: 10
Taken value: 44; Queue size is: 10
Taken value: 84; Queue size is: 10
Taken value: 23; Queue size is: 10
Taken value: 77; Queue size is: 9
Taken value: 33; Queue size is: 9
Taken value: 45; Queue size is: 10
Taken value: 61; Queue size is: 9
Taken value: 24; Queue size is: 9
Taken value: 9; Queue size is: 9
Taken value: 70; Queue size is: 9
Taken value: 52; Queue size is: 9
Taken value: 70; Queue size is: 9
Taken value: 69; Queue size is: 9

Learn to program Java Swing with my complete video course – desktop programming and applets. Includes 7 free videos. Click here for details.

All pages on this site are copyright © 2013 John W. Purcell

9 Responses to Java Multithreading: Producer-Consumer (Video Tutorial Part 7)

  1. Pingback: Stefen Havana

  2. Md Shahnawaz sakib says:

    Simple Awesome video

  3. Rohit says:

    Awesome stuff… Thanks

  4. Linda says:

    Hi.
    Thanks for greate video.
    Would you please explain what’s that mean by
    (random.nextInt(10) == 0) ?

    • Squiffy says:

      This is just a way of executing code only one in every ten times. random.nextInt(10) returns a random number from 0 to 9, so it’s only equal to 0 one tenth of the time.

      In retrospect, it would have made more sense just to make the Thread.sleep() sleep for a random amount of time.

  5. John says:

    how to make socket server with consumer and producer
    i should to put socket connection into consumer and producer or
    i should to put consumer and producer into socket connection

    i have client and multi-threaded server with (producer and consumer in each)

    • Squiffy says:

      I don’t really know enough about socket programming to answer. Maybe someone else knows. Or maybe I don’t understand your question. Don’t you just need a thread pool to service socket requests? Why would you need a producer/consumer?

  6. Jonathon Butler says:

    If I wanted to make the producer stop putting things in the que after it has put 7 items on the que, how would I do that?

  7. Aleksandar says:

    Here i had used Thread Pools, and is working fine :)
    ExecutorService executor = Executors.newFixedThreadPool(10);

    executor.submit(new Thread(new Runnable() {
    public void run() {
    try {
    producer();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }));

    executor.submit(new Thread(new Runnable() {
    public void run() {
    try {
    consumer();
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }));

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Posted in Java, Java Multithreading, Java Video Tutorials (Advanced) | Tagged , , , , |