import java.io.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
public class PipedThread {
public final static int MAX = 10;
static class SinkThread implements Runnable {
protected WritableByteChannel ch;
SinkThread(WritableByteChannel ch) {
this.ch = ch;
}
public void run() {
try {
ByteBuffer byteB = Charset.forName("ASCII").encode("Texte\n");
try { ch.write(byteB); } finally { ch.close(); }
} catch (IOException e) {
Thread.currentThread().interrupt();
}
}
}
static class SourceThread implements Runnable {
protected ReadableByteChannel ch;
SourceThread(ReadableByteChannel ch) {
this.ch = ch;
}
public void run() {
try {
try {
ByteBuffer byteB = ByteBuffer.allocate(MAX);
ch.read(byteB);
System.out.println(Thread.currentThread()+" received : ");
WritableByteChannel cout = Channels.newChannel(System.out);
byteB.flip();
cout.write(byteB);
} finally { ch.close(); }
} catch (IOException e) {
Thread.currentThread().interrupt();
}
}
}
public static void main(String[] args) throws IOException {
Pipe p = Pipe.open();
Pipe.SinkChannel sink = p.sink();
Pipe.SourceChannel source = p.source();
Thread t1 = new Thread(new SinkThread(sink),"Sink Thread");
Thread t2 = new Thread(new SourceThread(source),"Source Thread");
t1.start();
t2.start();
}
}