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 its run() API method. It has a BlockingQueue of Integers and in the run() 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, calling start() 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.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button