提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用辅助线程测试管道对象。
import java.nio.ByteBuffer; import java.nio.channels.Channels;//from nowjava import java.nio.channels.Pipe; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.Random; public class Main { public static void main(String[] argv) throws Exception { 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(); }/**from nowjava.com**/ } 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) { } }