java之PipedWriter和PipedReader

PipedWriter和PipedReader是管道读写,一般就是一个线程写,一个线程读,而且要先写后读。


测试代码:

package com.io;

import java.io.Closeable;
import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

import junit.framework.TestCase;

public class TestPipedWriterReader extends TestCase {

	public void testPipedWriterReader() {
		PipedWriter pipedWriter = null;
		PipedReader pipedReader = null;

		try {
			pipedWriter = new PipedWriter();
			pipedReader = new PipedReader();

			pipedWriter.connect(pipedReader);

			new Thread(new WriteRunnable(pipedWriter)).start();
			new Thread(new ReadRunnable(pipedReader)).start();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close(pipedWriter);
			close(pipedReader);
		}
	}

	private void close(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
				closeable = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	static class WriteRunnable implements Runnable {
		private PipedWriter pipedWriter = null;

		public WriteRunnable(PipedWriter pipedWriter) {
			this.pipedWriter = pipedWriter;
		}

		@Override
		public void run() {
			if (pipedWriter == null) {
				return;
			}
			try {
				pipedWriter.write("hello");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	static class ReadRunnable implements Runnable {
		private PipedReader pipedReader = null;

		public ReadRunnable(PipedReader pipedReader) {
			this.pipedReader = pipedReader;
		}

		@Override
		public void run() {
			if (pipedReader == null) {
				return;
			}
			try {

				if (pipedReader.ready()) {
					char[] cbuf = new char[1024];
					int len = 0;
					// cyclicBarrier.await();
					while ((len = pipedReader.read(cbuf)) != -1) {
						System.out.println(new String(cbuf, 0, len));
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}


你可能感兴趣的:(java)