| Refresh | Home EGTry.com

a simple example of coordination between the provider and the sonsumer


SynchronousQueue3Test.java

/*
 * Copyright@ 2011 www.egtry.com
 */

package egtry.thread.queue;

import java.util.Date;
import java.util.concurrent.SynchronousQueue;

//delivery a job face to face. Do leave at door
public class SynchronousQueue3Test {

  public static void main(String[] args) throws InterruptedException {

    SynchronousQueue<String> queue=new SynchronousQueue();
    Worker child1=new Worker(queue);
    child1.start();
    
    Worker child2=new Worker(queue);
    child2.start();
    
    System.out.println("putting a item into the queu");
    queue.put("first");
    
    System.out.println("putting another item into the queu");
    queue.put("second");
    
    System.out.println("Done");

  }
  
  public static class Worker extends Thread {
	  private final SynchronousQueue<String> queue;
	  
	  public Worker(SynchronousQueue<String> queue) {
		  this.queue=queue;
	  }
	  
	  @Override
	  public void run() {
		  System.out.println("taking the work item at child thread");
		  String item="";
		  try {
			  item=queue.take();
		  } catch (Exception e) {
			  
		  }
		  System.out.println("got the work item: "+item+" at: "+new Date());
	  }
  }
}



Output

taking the work item at child thread
putting a item into the queu
taking the work item at child thread
putting another item into the queu
Done
got the work item: second at: Mon Oct 03 12:01:05 CDT 2011
got the work item: first at: Mon Oct 03 12:01:05 CDT 2011