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 insynchronized
statement. The first one isaddWork(Object o)
and appends an object to the end of the list, usingaddLast(Object o)
API method of LinkedList. The second method, isgetWork()
and removes and returns the first element of the list, usingremoveFirst()
API method of LinkedList. If the list is empty, it keeps waiting, usingwait()
API method of Object that causes the thread invoked to this object to wait until another thread calls thenotify()
API method of Object for this object. - We have also created a class,
Worker
that extends the Thread and overrides itsrun()
API method. It has aWorkQueue
object and in itsrun()
method it callsgetWork()
method ofWorker
forever. - We create a new instance of
WorkQueue
and use it to create two newWorker
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, callingaddWork(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.