title: Java "conversation" between 2 threads: Piped Input/Output streams
body: <p>I would like to know what is in your opinion the best way of implementing a program where two threads are exchanging Strings and responding to each other.</p>
  
  <p>I couldn't get it to work, either with java.nio.Pipe and java.io.PipedInputStream / java.io.PipedOutput.Stream</p>
  
  <p>Here is a code example of what I want to do:</p>
  
  <p>The main class, setting everything up.</p>
  
  <pre><code>public static void main(String[] args) {
          // TODO
          // Create two communication channel, and bind them together
  
          MyThread t1 = new MyThread(channel1Reader, channel2Writer, 0);
          MyThread t2 = new MyThread(channel2Reader, channel1Writer, 1);
  
          t1.run();
          t2.run();
  
      }
  </code></pre>
  
  <p>The thread class:</p>
  
  <pre><code>public class MyThread extends Thread {
      private ? inputStream;
      private ? outputStream;
      private boolean canTalk;
      private int id;
  
      public MyThread(? inputStream, ? outputStream, boolean isStarting, int id) {
          this.inputStream = inputStream;
          this.outputStream = outputStream;
          this.canTalk = isStarting;
          this.id = id;
      }
  
      public void run() {
          while(true) {
              if(canTalk) {
                  String s = getRandomWord();
                  // TODO
                  // Write s to the output stream
              }
  
              // TODO
              // Wait until receiving a String on the input stream
              String s2 = the word I just received
              Log.info("Thread " + id + " received the word '" + s2 + "'");
              canTalk = true;
              Thread.sleep(1000);
          }
      }
  </code></pre>
  
  <p>Any ideas?</p>
  
  <p>Thanks!</p>