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,
WorkQueuethat has aLinkedList of Objects and two methods insynchronizedstatement. 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 ofObject that causes the thread invoked to this object to wait until another thread calls thenotify()API method ofObject for this object. - We have also created a class,
Workerthat extends theThread and overrides itsrun()API method. It has aWorkQueueobject and in itsrun()method it callsgetWork()method ofWorkerforever. - We create a new instance of
WorkQueueand use it to create two newWorkerthreads. - 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:
123456879101112141315161718...
This was an example of an unbounded work queue in Java.
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!
We will contact you soon.
Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor atJava Code Geeks.



