Source Code : Implementing an Unbounded Work Queue

Java Is Open Source Programming Language You Can Download From Java and Java Libraries From http://www.oracle.com. Click Here to download
We provide this code related to title for you to solve your developing problem easily. Libraries which is import in this program you can download from http://www.oracle.com. Click Here or search from google with Libraries Name you get jar file related it

Implementing an Unbounded Work Queue

  

import java.util.LinkedList;

public class Main {
  public static void main(String[] argv) {
    WorkQueue queue = new WorkQueue();

    int numWorkers = 2;
    Worker[] workers = new Worker[numWorkers];
    for (int i = 0; i < workers.length; i++) {
      workers[i] = new Worker(queue);
      workers[i].start();
    }

    for (int i = 0; i < 100; i++) {
      queue.addWork(i);
    }
  }
}

class WorkQueue {
  LinkedList<Object> queue = new LinkedList<Object>();

  public synchronized void addWork(Object o) {
    queue.addLast(o);
    notify();
  }

  public synchronized Object getWork() throws InterruptedException {
    while (queue.isEmpty()) {
      wait();
    }
    return queue.removeFirst();
  }
}

class Worker extends Thread {
  WorkQueue q;

  Worker(WorkQueue q) {
    this.q = q;
  }

  public void run() {
    try {
      while (true) {
        Object x = q.getWork();

        if (x == null) {
          break;
        }
        System.out.println(x);
      }
    } catch (InterruptedException e) {
    }
  }
}

   
    
  

Thank with us