Communicate between threads using a Queue : Collections Threads « Threads « Java






Communicate between threads using a Queue

   

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

class PrepareProduction implements Runnable {
  BlockingQueue<String> queue;

  PrepareProduction(BlockingQueue<String> q) {
    queue = q;
  }

  public void run() {
    String thisLine;
    try {
      queue.put("1");
      queue.put("done");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

class DoProduction implements Runnable {
  private final BlockingQueue<String> queue;

  DoProduction(BlockingQueue<String> q) {
    queue = q;
  }

  public void run() {
    try {
      String value = queue.take();
      while (!value.equals("done")) {
        value = queue.take();
        System.out.println(value);
      }
    } catch (Exception e) {
      System.out.println(Thread.currentThread().getName() + " "
          + e.getMessage());
    }
  }
}

public class Main {
  public static void main(String[] args) throws Exception {
    BlockingQueue<String> q = new LinkedBlockingQueue<String>();
    Thread p1 = new Thread(new PrepareProduction(q));
    Thread c1 = new Thread(new DoProduction(q));
    p1.start();
    c1.start();
    p1.join();
    c1.join();
  }
}

   
    
    
  








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.Using a Thread-Local Variable
10.A work queue is used to coordinate work between a producer and a set of worker threads.
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