A work queue is used to coordinate work between a producer and a set of worker threads. : Collections Threads « Threads « Java






A work queue is used to coordinate work between a producer and a set of worker threads.

   

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) {
    }
  }
}

   
    
    
  








Related examples in the same category

1.Java 1.5 (5.0) new features: PriorityQueueJava 1.5 (5.0) new features: PriorityQueue
2.Safe list copySafe list copy
3.Safe vector copySafe vector copy
4.Safe collection operationSafe collection operation
5.Java 1.5 (5.0) new feature: collection and thread
6.Java Thread Performance: Collection Test
7.Java Thread Performance: AtomicTest
8.Rhyming WordsRhyming Words
9.Communicate between threads using a Queue
10.Using a Thread-Local Variable
11.Return a value from a thread.
12.A multithreaded queue used for implementing producer-consumer style threading patternsA multithreaded queue used for implementing producer-consumer style threading patterns
13.Customized java.util.ArrayList: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
14.Customized java.util.HashMap: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
15.Customized java.util.TreeMap: operate in a multithreaded environment where the large majority of method calls are read-only, instead of structural changes.
16.Current set