threads
Bounded work queue example
In this example we shall show you how to create a use a bounded work queue. To create and use a bounded work queue we have followed the below steps:
- We have created a
Worker
that extends the Thread and overrides itsrun()
API method. It has a BlockingQueue of Integers and in therun()
method it keeps retrieving and removing elements from the queue, waiting if necessary until an element becomes available. - We created a BlockingQueue of Integers and a number of
Worker
threads and started their execution, callingstart()
method of Thread. - Then we put elements to the queue, using
put(Integer e)
API method of BlockingQueue,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class Main { public static void main(String[] argv) throws Exception { int size = 10; BlockingQueue<Integer> bQueue = new ArrayBlockingQueue<Integer>(size); int thread_c = 2; Worker[] workers = new Worker[thread_c]; for (int i = 0; i < workers.length; i++) { workers[i] = new Worker(bQueue); workers[i].start(); } for (int i = 0; i < 100; i++) { bQueue.put(i); } } } class Worker extends Thread { BlockingQueue<Integer> val; Worker(BlockingQueue<Integer> bque) { this.val = bque; } @Override public void run() { try { while (true) { Integer i = val.take(); if (i == null) { break; } System.out.println(i); } } catch (InterruptedException ex) { } } }
Output:
1
2
3
4
5
6
8
7
9
10
11
12
14
13
15
16
.
.
.
This was an example of how create a use a bounded work queue to in Java.