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

📄 pipedstreamexam.java

📁 Java程序设计实用教程源代码 本书源代码按章分别放置在不同的文件夹中,所有程序均在JDK1.6环境下编译运行正常,除了第13章需要建立ODBC数据源之外,其他程序只要有Java运行环境即可直接运行
💻 JAVA
字号:
import java.io.*;
public class PipedStreamExam {
  public static void main(String args[]) throws IOException {
    try {
      //Sender和Receiver类是Thread类的子类
      Sender t1 = new Sender();
      Receiver t2 = new Receiver();
      //分别从线程t1和t2获取输入输出管道流pin和pout
      PipedOutputStream pout = t1.getOutputStream();
      PipedInputStream pin = t2.getInputStream();
      pout.connect(pin);
      t1.start(); //启动线程t1
      t2.start(); //启动线程t2
    }
    catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}
class Sender extends Thread { //定义继承自Thread类的Sender类
  private PipedOutputStream pout = new PipedOutputStream();
  public PipedOutputStream getOutputStream() {
    return pout;
  }
  public void run() { //重载父类的run()方法。线程运行的代码。
    String s = new String("Hello,receiver,how are you?");
    try {
      //将数字0~4写至管道输出流
      for(int i = 0;i<5;i++){
      	pout.write(i);
      }
      //将s字符串写至管道输出流
      pout.write(s.getBytes());
      pout.close();
    }
    catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}
class Receiver extends Thread { //定义继承自Thread类的Receiver类
  private PipedInputStream pin = new PipedInputStream();
  public PipedInputStream getInputStream() {
    return pin;
  }
  public void run() {
    String s = null;
    byte[] buf = new byte[1024];
    try { //接收管道输入流中的数据并存放到buf数组中
    	int c ,i = 0;
    	System.out.print("Receive 5 numbers: ");
    	while(i++<5&&(c = pin.read())!= -1)
    		System.out.print(c);
      int len = pin.read(buf);
      s = new String(buf, 0, len); //基于buf的内容创建String对象s
      System.out.println("\nThe following string comes from sender:" + s);
      pin.close();
    }
    catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

⌨️ 快捷键说明

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