pipe.java

来自「翁剀JAVA语言那门课程的教案 很多人都看多他的视频教程可惜没有ppt的教案」· Java 代码 · 共 65 行

JAVA
65
字号
//: Pipe.java

import java.io.*;

public class Pipe {
	public static void main(String[] args) throws Exception {
		PipedInputStream in = new PipedInputStream();
		PipedOutputStream out = new PipedOutputStream(in);
		
		Sender s = new Sender(out);
		Receiver r = new Receiver(in);
		Thread t1 = new Thread(s);
		Thread t2 = new Thread(r);
		t1.start();
		t2.start();
		t2.join();	//	for M$Win/JDK-1.0.2
	}
}

class Sender implements Runnable {
	OutputStream out;
	
	public Sender(OutputStream out) {
		this.out = out;
	}
	
	public void run() {
		byte value;
		
		try {
			for ( int i=0; i<5; i++ ) {
				value = (byte)(Math.random()*256);
				System.out.print("About to send "+value+".. ");
				out.write(value);
				System.out.println(" ..sent.");
				Thread.sleep((long)(Math.random()*1000));
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class Receiver implements Runnable {
	InputStream in;
	
	public Receiver(InputStream in) {
		this.in = in;
	}
	
	public void run() {
		int value;
		
		try {
			while ( (value = in.read()) != -1 ) {
				System.out.println("received "+(byte)value+".");
			}
			System.out.println("Pipe closed.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
	

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?