Java Exchanger class

Introduction

Java Exchanger class can simplify the exchange of data between two threads.

It waits until two separate threads call its exchange() method.

Here is an example that demonstrates Exchanger.

// An example of Exchanger. 

import java.util.concurrent.Exchanger;

public class Main {
  public static void main(String args[]) {
    Exchanger<String> exgr = new Exchanger<String>();

    new UseString(exgr);
    new MakeString(exgr);
  }//w  w w.  ja  v a2s.  c  om
}

// A Thread that constructs a string.
class MakeString implements Runnable {
  Exchanger<String> ex;
  String str;

  MakeString(Exchanger<String> c) {
    ex = c;
    str = new String();

    new Thread(this).start();
  }

  public void run() {
    char ch = 'A';

    for (int i = 0; i < 3; i++) {

      // Fill Buffer
      for (int j = 0; j < 5; j++)
        str += ch++;

      try {
        str = ex.exchange(str);
      } catch (InterruptedException exc) {
        System.out.println(exc);
      }
    }
  }
}

class UseString implements Runnable {
  Exchanger<String> ex;
  String str;

  UseString(Exchanger<String> c) {
    ex = c;
    new Thread(this).start();
  }

  public void run() {

    for (int i = 0; i < 3; i++) {
      try {
        // Exchange an empty buffer for a full one.
        str = ex.exchange(new String());
        System.out.println("Got: " + str);
      } catch (InterruptedException exc) {
        System.out.println(exc);
      }
    }
  }
}



PreviousNext

Related