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.
I couldn't get it to work, either with java.nio.Pipe and java.io.PipedInputStream / java.io.PipedOutput.Stream
Here is a code example of what I want to do:
The main class, setting everything up.
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();
}
The thread class:
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);
}
}
Any ideas?
Thanks!