⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 d0da4af85875001d187dee36bb048aa6

📁 java程序设计教程的源码
💻
字号:
//【例9-14】  利用管道来实现线程间的通信
//程序清单9-14: Example9_14.java
import java.io.*;

public class Example9_14 {
	public static void main(String[] args) { // 创建一个主线程
		Example9_14 pipeapp = new Example9_14();
		// 为input.txt文件创建输入流fileln
		try { 
			FileInputStream xfileln = new FileInputStream("input.txt");
			// 启动将输入数据"x"改变到"y"的线程ythread
			InputStream ylnpipe = pipeapp.changetoy(xfileln);
			// 启动数据从"y"改变到"z"的线程zthread
			InputStream zlnpipe = pipeapp.changetoz(ylnpipe);
			System.out.println();
			System.out.println("Here are the results:");
			System.out.println();
			DataInputStream inputstream = new DataInputStream(zlnpipe);
			String str = inputstream.readLine(); // 每次读一行
			while (str != null) {
				System.out.println(str);
				str = inputstream.readLine();
			}
			inputstream.close(); // 关闭输入流
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	public InputStream changetoy(InputStream inputstream) {
		try {
			DataInputStream xfileln = new DataInputStream(inputstream);
			PipedOutputStream pipeout = new PipedOutputStream(); // 创建一个新的管道
			PipedInputStream pipeln = new PipedInputStream(pipeout);
			// 输出管道定位到printstream
			PrintStream printstream = new PrintStream(pipeout);
			Ythread ythread = new Ythread(xfileln, printstream);
			ythread.start();
			return pipeln;
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return null;
	}

	public InputStream changetoz(InputStream inputsteam) {
		try {
			DataInputStream yfileln = new DataInputStream(inputsteam);
			PipedOutputStream pipeout2 = new PipedOutputStream();
			PipedInputStream pipeln2 = new PipedInputStream(pipeout2);
			PrintStream printstream2 = new PrintStream(pipeout2);
			Zthread zthread = new Zthread(yfileln, printstream2);
			zthread.start();
			return pipeln2;
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		return null;
	}
}

⌨️ 快捷键说明

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