パイプ(pipe)の例(コメント付き)


pipe説明
パイプラインは、同じJava仮想マシン内でのみデータを転送するために使用できます.スレッド間でデータを転送するより効率的な方法があるが、パイプを使用する利点は、パッケージング性にある.1
code
package com.nio.demo;

import java.io.IOException;
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 {
		//         ,              
		WritableByteChannel out = Channels.newChannel(System.out);
		//        ,       ,          
		ReadableByteChannel readableByteChannel = startWorker(10);
		//       ,          
		ByteBuffer buffer = ByteBuffer.allocate(100);
		//               ,            ,        
		while(readableByteChannel.read(buffer)>=0) {
			//                    
			buffer.flip();
			//      
			out.write(buffer);
			//     
			buffer.clear();
		}

	}

	private static ReadableByteChannel startWorker(int reps) throws Exception {
		//      
		Pipe pipe = Pipe.open();
		//      ,         (pipe.sink())
		Worker worker=new Worker(pipe.sink(), reps);
		worker.start();
		//        
		return (pipe.source());
	}
	//     
	private static class Worker extends Thread {
		WritableByteChannel channel;
		private int reps;

		public Worker(WritableByteChannel channel, int reps) {
			this.channel = channel;
			this.reps = reps;
		}

		@Override
		public void run() {
			ByteBuffer buffer = ByteBuffer.allocate(100);
			try {
				for (int i = 0; i < reps; i++) {
					doSomeWork(buffer);
					while (channel.write(buffer) > 0) {
						// empty
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		private String[] products = { "No good deed goes unpunished", "To be, or what?",
				"No matter where you go, there you are", "Just say \"Yo\"", "My karma ran over my dogma" };
		private Random rand = new Random();

		private void doSomeWork(ByteBuffer buffer) {
			int product = rand.nextInt(products.length);
			buffer.clear();
			buffer.put(products[product].getBytes());
			buffer.put("\r
".getBytes()); buffer.flip(); } } }

《Java Nio》 ↩︎