threads
Worker coordination using WorkQueue
In this example we shall show you how to achieve a coordination between two threads that try to get the same objects. The steps of the example are described below:
- We have created a class,
WorkerQueue
, that has a LinkedList of Objects. In itssynchronized void addWork(Object o)
method it appends the object to the end of the list, withaddLast(Object e)
API method of LinkedList and then callsnotify()
API method of Object to wake up the thread waiting for it. In itssynchronized Object getWork()
method it waits until the list is empty, callingwait()
API method of Object and it usesremoveFirst()
API method of LinkedList to remove and return the first element of the list. Since both methods are insynchronized
statement, it is not possible for two invocations of them on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. - We have also created a class,
Worker
that extends the Thread. It has aWorkerQueue
and it overrides therun()
API method of the Thread. In this method, it sets an Object to work, calling thegetWork()
method of WorkerQueue forever. - We create a new
WorkerQueue
and two newWorker
threads with the same WorkerQueue above created and call theirstart()
API method to start execution. The we calladdWork(Object o)
method of theWorkerQueue
for a number of objects. The WorkerQueue is the same for the two threads, so it coordinates the work between the two threads. The added to the list objects are removed from the list by the threads, since in theirrun()
method they constantly try to get the objects,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.LinkedList; public class CoordinationExampe { public static void main(String[] argv) { WorkerQueue workqueue = new WorkerQueue(); int threads = 2; Worker[] workth = new Worker[threads]; for (int i = 0; i < workth.length; i++) { workth[i] = new Worker(workqueue); workth[i].start(); } for (int i = 0; i < 100; i++) { workqueue.addWork(i); } } } class WorkerQueue { LinkedList<Object> q = new LinkedList<Object>(); public synchronized void addWork(Object obj) { q.addLast(obj); notify(); } public synchronized Object getWork() throws InterruptedException { while (q.isEmpty()) { wait(); } return q.removeFirst(); } } class Worker extends Thread { WorkerQueue q; Worker(WorkerQueue q) { this.q = q; } @Override public void run() { try { while (true) { Object o = q.getWork(); if (o == null) { break; } System.out.println(o); } } catch (InterruptedException ex) { } } }
This was an example of how to achieve a coordination between two threads that try to get the same objects in Java.