threads

Unbounded work queue example

This is an example of an unbounded work queue. The steps of creating and using an unbounded work queue are described below:

  • We have created a class, WorkQueue that has a LinkedList of Objects and two methods in synchronized statement. The first one is addWork(Object o) and appends an object to the end of the list, using addLast(Object o) API method of LinkedList. The second method, is getWork() and removes and returns the first element of the list, using removeFirst() API method of LinkedList. If the list is empty, it keeps waiting, using wait() API method of Object that causes the thread invoked to this object to wait until another thread calls the notify() API method of Object for this object.
  • We have also created a class, Worker that extends the Thread and overrides its run() API method. It has a WorkQueue object and in its run() method it calls getWork() method of Worker forever.
  • We create a new instance of WorkQueue and use it to create two new Worker threads.
  • We begin the threads’ execution, using start() API method of Thread, so the threads start retrieving elements from the list, and we also add elements to the list, calling addWork(Object o) method of Worker.

Let’s take a look at the code snippet that follows: 

package com.javacodegeeks.snippets.core;

import java.util.LinkedList;

public class Main {

    public static void main(String[] argv) {

  

  WorkQueue workQueue = new WorkQueue();


  int numthreads = 2;

  

  Worker[] workers = new Worker[numthreads];

  

  for (int i = 0; i < workers.length; i++) {


workers[i] = new Worker(workQueue);


workers[i].start();

  }


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


workQueue.addWork(i);

  }
    }
}

class WorkQueue {

    LinkedList<Object> workQueue = new LinkedList<Object>();

    public synchronized void addWork(Object o) {

  workQueue.addLast(o);

  notify();
    }

    public synchronized Object getWork() throws InterruptedException {

  while (workQueue.isEmpty()) {


wait();

  }

  return workQueue.removeFirst();
    }
}

class Worker extends Thread {

    WorkQueue queue;

    Worker(WorkQueue queue) {

  this.queue = queue;
    }

    @Override
    public void run() {

  try {


while (true) {


    


    Object x = queue.getWork();



    if (x == null) {



  break;


    }


    System.out.println(x);


}

  } catch (InterruptedException ex) {

  }
    }
}

Output:

1
2
3
4
5
6
8
7
9
10
11
12
14
13
15
16
17
18
.
.
.

 
This was an example of an unbounded work queue in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He 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