这个pipe和linux系统上用来连接两个进程的pipe不是同一概念,
主要是在JVM内部,用来实现不同线程之间的数据同步。
这倒让我想起了go语言的channel技术。
package com.ronsoft.books.nio.channels;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Random;
public class PipeTest {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
WritableByteChannel out = Channels.newChannel(System.out);
ReadableByteChannel workerChannel = startWorker(10);
ByteBuffer buffer = ByteBuffer.allocate(100);
while (workerChannel.read(buffer) >= 0) {
buffer.flip();
out.write(buffer);
buffer.clear();
}
}
private static ReadableByteChannel startWorker(int reps) throws Exception {
Pipe pipe = Pipe.open();
Worker worker = new Worker(pipe.sink(), reps);
worker.start();
return (pipe.source());
}
private static class Worker extends Thread {
WritableByteChannel channel;
private int reps;
Worker(WritableByteChannel channel, int reps) {
this.channel = channel;
this.reps = reps;
}
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(100);
try {
for (int i = 0; i < this.reps; i++) {
doSomeWork(buffer);
while (channel.write(buffer) > 0) {
}
}
this.channel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private static String [] products = {
"No good deed ges unpunished",
"To be, or what?",
"No matter where you go, there you are",
"Just say \"Yo\"",
"My karma ran over my dogma"
};
private static Random rand = new Random();
private static void doSomeWork(ByteBuffer buffer) {
int product = rand.nextInt(products.length);
buffer.clear();
buffer.put(products[product].getBytes());
buffer.put("\r\n".getBytes());
buffer.flip();
}
}
Just say "Yo"
No good deed ges unpunished
To be, or what?
No good deed ges unpunished
To be, or what?
Just say "Yo"
Just say "Yo"
No matter where you go, there you are
No good deed ges unpunished
Just say "Yo"