| Refresh | Home EGTry.com

exechange data between two threads by a blocking handshake


Exchanger1Test.java

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

package egtry.thread.queue;

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

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

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

    Exchanger<String> queue=new Exchanger<String>();
    Worker child1=new Worker(queue);
    child1.start();
    
    String result=queue.exchange("From parent");
    System.out.println("Received data from child: "+result);
	
  }
  
  public static class Worker extends Thread {
	  private final Exchanger<String> queue;
	  
	  public Worker(Exchanger<String> queue) {
		  this.queue=queue;
	  }
	  
	  @Override
	  public void run() {
		  System.out.println("Child Thread");
		  String item="";
		  try {
			  item=queue.exchange("From Child");
		  } catch (Exception e) {
			  
		  }
		  System.out.println("got data from parent:  "+item);
	  }
  }
}



Output

Child Thread
got data from parent:  From parent
Received data from child: From Child