How to Use BlockingQueue in Java


In this example we will show how to use BlockingQueue.

Source Code

package com.beginner.examples;

import java.util.concurrent.*;

public class BlockingQueueExample {
	public static void main(String[] args) {
		final BlockingQueue queue = new ArrayBlockingQueue(3);
		new Thread() {
			public void run() {
				while(true) {
					try {
						Thread.sleep((long)(Math.random()*10000));
						// put data
						queue.put(10);
						System.out.println(Thread.currentThread().getName() + " is putting data,time: " + System.currentTimeMillis());
					}catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		
		new Thread() {
			public void run() {
				while(true) {
					try {
						Thread.sleep((long)(Math.random()*10000));
						// put data
						queue.put(20);
						System.out.println(Thread.currentThread().getName() + " is putting data,time: " + System.currentTimeMillis());
					}catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
		
		new Thread() {
			public void run() {
				while(true) {
					try{
						//sleep 200
						Thread.sleep(200);
						// get data
						queue.take();
						System.out.println(Thread.currentThread().getName()+ " is getting data,time: " + System.currentTimeMillis());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}
}

Output:

Thread-1 is putting data,time: 1561715911259
Thread-2 is getting data,time: 1561715911259
Thread-2 is getting data,time: 1561715915466
Thread-0 is putting data,time: 1561715915467
Thread-1 is putting data,time: 1561715918810
Thread-2 is getting data,time: 1561715918810
Thread-0 is putting data,time: 1561715922993
Thread-2 is getting data,time: 1561715922993
Thread-0 is putting data,time: 1561715924102
Thread-2 is getting data,time: 1561715924102
Thread-2 is getting data,time: 1561715924488
Thread-1 is putting data,time: 1561715924488
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments