Exchanger sample code

2156 ワード

Runnable version of sample code in Exchanger's javadoc.
 
import java.util.concurrent.Exchanger;

public class FillAndEmpty {
  static String PART = "abcde";
  static int PART_LEN = 5;
  static int STEP_COUNT = 10;
  
  Exchanger<StringBuilder> exchanger = new Exchanger<StringBuilder>();
  StringBuilder initialEmptyBuffer = new StringBuilder(50);
  StringBuilder initialFullBuffer = new StringBuilder(50);

  class FillingLoop implements Runnable {
    StringBuilder currentBuffer = initialEmptyBuffer;
    @Override
    public void run() {
      try {
        while (currentBuffer != null) {
          currentBuffer.append(PART);
          if (currentBuffer.length() == PART_LEN * STEP_COUNT) {
            System.out.println("full buffer: " + currentBuffer);
            currentBuffer = exchanger.exchange(currentBuffer);
          }
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  class EmptyingLoop implements Runnable {
    @Override
    public void run() {
      StringBuilder currentBuffer = initialFullBuffer;
      try {
        while (currentBuffer != null) {
          currentBuffer.setLength(currentBuffer.length() - PART_LEN);
          if (currentBuffer.length() == 0) {
            System.out.println("empty buffer: " + currentBuffer);
            currentBuffer = exchanger.exchange(currentBuffer);
          }
        }
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  void start() {
    for (int i = 0; i < STEP_COUNT; i++)
      initialFullBuffer.append(PART);
    new Thread(new FillingLoop()).start();
    new Thread(new EmptyingLoop()).start();
  }

  public static void main(String[] args) {
    FillAndEmpty fae = new FillAndEmpty();
    fae.start();
  }
}