当前位置: 移动技术网 > IT编程>开发语言>Java > 举例讲解Java中Piped管道输入输出流的线程通信控制

举例讲解Java中Piped管道输入输出流的线程通信控制

2019年07月22日  | 移动技术网IT编程  | 我要评论

pipedoutputstream和pipedinputstream

在java中,pipedoutputstream和pipedinputstream分别是管道输出流和管道输入流。
它们的作用是让多线程可以通过管道进行线程间的通讯。在使用管道通信时,必须将pipedoutputstream和pipedinputstream配套使用。
使用管道通信时,大致的流程是:我们在线程a中向pipedoutputstream中写入数据,这些数据会自动的发送到与pipedoutputstream对应的pipedinputstream中,进而存储在pipedinputstream的缓冲中;此时,线程b通过读取pipedinputstream中的数据。就可以实现,线程a和线程b的通信。
下面,我们看看多线程中通过管道通信的例子。例子中包括3个类:receiver.java, pipedstreamtest.java 和 sender.java。
receiver.java的代码如下:

import java.io.ioexception; 

import java.io.pipedinputstream; 

@suppresswarnings("all") 
/** 
 * 接收者线程 
 */ 
public class receiver extends thread {

 // 管道输入流对象。
 // 它和“管道输出流(pipedoutputstream)”对象绑定,
 // 从而可以接收“管道输出流”的数据,再让用户读取。
 private pipedinputstream in = new pipedinputstream(); 

 // 获得“管道输入流”对象
 public pipedinputstream getinputstream(){ 
  return in; 
 } 

 @override
 public void run(){ 
  readmessageonce() ;
  //readmessagecontinued() ;
 }

 // 从“管道输入流”中读取1次数据
 public void readmessageonce(){
  // 虽然buf的大小是2048个字节,但最多只会从“管道输入流”中读取1024个字节。
  // 因为,“管道输入流”的缓冲区大小默认只有1024个字节。
  byte[] buf = new byte[2048];
  try {
   int len = in.read(buf);
   system.out.println(new string(buf,0,len));
   in.close();
  } catch (ioexception e) {
   e.printstacktrace();
  }
 }
 // 从“管道输入流”读取>1024个字节时,就停止读取
 public void readmessagecontinued() {
  int total=0;
  while(true) {
   byte[] buf = new byte[1024];
   try {
    int len = in.read(buf);
    total += len;
    system.out.println(new string(buf,0,len));
    // 若读取的字节总数>1024,则退出循环。
    if (total > 1024)
     break;
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }

  try {
   in.close();
  } catch (ioexception e) {
   e.printstacktrace();
  }
 }
}

sender.java的代码如下:

import java.io.ioexception; 

import java.io.pipedoutputstream; 
@suppresswarnings("all")
/** 
 * 发送者线程 
 */ 
public class sender extends thread {

 // 管道输出流对象。
 // 它和“管道输入流(pipedinputstream)”对象绑定,
 // 从而可以将数据发送给“管道输入流”的数据,然后用户可以从“管道输入流”读取数据。
 private pipedoutputstream out = new pipedoutputstream();

 // 获得“管道输出流”对象
 public pipedoutputstream getoutputstream(){
  return out;
 } 

 @override
 public void run(){ 
  writeshortmessage();
  //writelongmessage();
 } 

 // 向“管道输出流”中写入一则较简短的消息:"this is a short message" 
 private void writeshortmessage() {
  string strinfo = "this is a short message" ;
  try {
   out.write(strinfo.getbytes());
   out.close(); 
  } catch (ioexception e) { 
   e.printstacktrace(); 
  } 
 }
 // 向“管道输出流”中写入一则较长的消息
 private void writelongmessage() {
  stringbuilder sb = new stringbuilder();
  // 通过for循环写入1020个字节
  for (int i=0; i<102; i++)
   sb.append("0123456789");
  // 再写入26个字节。
  sb.append("abcdefghijklmnopqrstuvwxyz");
  // str的总长度是1020+26=1046个字节
  string str = sb.tostring();
  try {
   // 将1046个字节写入到“管道输出流”中
   out.write(str.getbytes());
   out.close();
  } catch (ioexception e) {
   e.printstacktrace();
  }
 }
}

pipedstreamtest.java的代码如下:

import java.io.pipedinputstream;
import java.io.pipedoutputstream;
import java.io.ioexception;

@suppresswarnings("all") 
/** 
 * 管道输入流和管道输出流的交互程序
 */ 
public class pipedstreamtest {

 public static void main(string[] args) { 
  sender t1 = new sender(); 

  receiver t2 = new receiver(); 

  pipedoutputstream out = t1.getoutputstream(); 

  pipedinputstream in = t2.getinputstream(); 

  try { 
   //管道连接。下面2句话的本质是一样。
   //out.connect(in); 
   in.connect(out); 

   /** 
    * thread类的start方法: 
    * 使该线程开始执行;java 虚拟机调用该线程的 run 方法。 
    * 结果是两个线程并发地运行;当前线程(从调用返回给 start 方法)和另一个线程(执行其 run 方法)。 
    * 多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。 
    */
   t1.start();
   t2.start();
  } catch (ioexception e) {
   e.printstacktrace();
  }
 }
}

运行结果:

this is a short message

说明:
(1) in.connect(out);将“管道输入流”和“管道输出流”关联起来。查看pipedoutputstream.java和pipedinputstream.java中connect()的源码;我们知道 out.connect(in); 等价于 in.connect(out);
(2)

t1.start(); // 启动“sender”线程 
t2.start(); // 启动“receiver”线程

先查看sender.java的源码,线程启动后执行run()函数;在sender.java的run()中,调用writeshortmessage();
writeshortmessage();的作用就是向“管道输出流”中写入数据"this is a short message" ;这条数据会被“管道输入流”接收到。下面看看这是如何实现的。
先看write(byte b[])的源码,在outputstream.java中定义。pipedoutputstream.java继承于outputstream.java;outputstream.java中write(byte b[])的源码如下:

public void write(byte b[]) throws ioexception {
 write(b, 0, b.length);
}

实际上write(byte b[])是调用的pipedoutputstream.java中的write(byte b[], int off, int len)函数。查看write(byte b[], int off, int len)的源码,我们发现:它会调用 sink.receive(b, off, len); 进一步查看receive(byte b[], int off, int len)的定义,我们知道sink.receive(b, off, len)的作用就是:将“管道输出流”中的数据保存到“管道输入流”的缓冲中。而“管道输入流”的缓冲区buffer的默认大小是1024个字节。
至此,我们知道:t1.start()启动sender线程,而sender线程会将数据"this is a short message"写入到“管道输出流”;而“管道输出流”又会将该数据传输给“管道输入流”,即而保存在“管道输入流”的缓冲中。
接下来,我们看看“用户如何从‘管道输入流'的缓冲中读取数据”。这实际上就是receiver线程的动作。
t2.start() 会启动receiver线程,从而执行receiver.java的run()函数。查看receiver.java的源码,我们知道run()调用了readmessageonce()。
而readmessageonce()就是调用in.read(buf)从“管道输入流in”中读取数据,并保存到buf中。
通过上面的分析,我们已经知道“管道输入流in”的缓冲中的数据是"this is a short message";因此,buf的数据就是"this is a short message"。
为了加深对管道的理解。我们接着进行下面两个小试验。
试验一:修改sender.java

public void run(){ 
 writeshortmessage();
 //writelongmessage();
} 

修改为

public void run(){ 
 //writeshortmessage();
 writelongmessage();
}

运行程序。运行结果为:

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
012345678901234567890123456789abcd

这些数据是通过writelongmessage()写入到“管道输出流”,然后传送给“管道输入流”,进而存储在“管道输入流”的缓冲中;再被用户从缓冲读取出来的数据。
然后,观察writelongmessage()的源码。我们可以发现,str的长度是1046个字节,然后运行结果只有1024个字节!为什么会这样呢?
道理很简单:管道输入流的缓冲区默认大小是1024个字节。所以,最多只能写入1024个字节。
观察pipedinputstream.java的源码,我们能了解的更透彻。

private static final int default_pipe_size = 1024;
public pipedinputstream() {
 initpipe(default_pipe_size);
}

默认构造函数调用initpipe(default_pipe_size),它的源码如下:

private void initpipe(int pipesize) {
  if (pipesize <= 0) {
  throw new illegalargumentexception("pipe size <= 0");
  }
  buffer = new byte[pipesize];
}

从中,我们可以知道缓冲区buffer的默认大小就是1024个字节。
试验二: 在“试验一”的基础上继续修改receiver.java

public void run(){ 
 readmessageonce() ;
 //readmessagecontinued() ;
}

修改为

public void run(){ 
 //readmessageonce() ;
 readmessagecontinued() ;
}

运行程序。运行结果为:

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
012345678901234567890123456789abcd
efghijklmnopqrstuvwxyz

这个结果才是writelongmessage()写入到“输入缓冲区”的完整数据。

pipedwriter和pipedreader
pipedwriter 是字符管道输出流,它继承于writer。
pipedreader 是字符管道输入流,它继承于writer。
pipedwriter和pipedreader的作用是可以通过管道进行线程间的通讯。在使用管道通信时,必须将pipedwriter和pipedreader配套使用。
下面,我们看看多线程中通过pipedwriter和pipedreader通信的例子。例子中包括3个类:receiver.java, sender.java 和 pipetest.java
receiver.java的代码如下:

import java.io.ioexception; 

import java.io.pipedreader; 

@suppresswarnings("all") 
/** 
 * 接收者线程 
 */ 
public class receiver extends thread { 

 // 管道输入流对象。
 // 它和“管道输出流(pipedwriter)”对象绑定,
 // 从而可以接收“管道输出流”的数据,再让用户读取。
 private pipedreader in = new pipedreader(); 

 // 获得“管道输入流对象”
 public pipedreader getreader(){ 
  return in; 
 } 

 @override
 public void run(){ 
  readmessageonce() ;
  //readmessagecontinued() ;
 }

 // 从“管道输入流”中读取1次数据
 public void readmessageonce(){ 
  // 虽然buf的大小是2048个字符,但最多只会从“管道输入流”中读取1024个字符。
  // 因为,“管道输入流”的缓冲区大小默认只有1024个字符。
  char[] buf = new char[2048]; 
  try { 
   int len = in.read(buf); 
   system.out.println(new string(buf,0,len)); 
   in.close(); 
  } catch (ioexception e) { 
   e.printstacktrace(); 
  } 
 }

 // 从“管道输入流”读取>1024个字符时,就停止读取
 public void readmessagecontinued(){
  int total=0;
  while(true) {
   char[] buf = new char[1024];
   try {
    int len = in.read(buf);
    total += len;
    system.out.println(new string(buf,0,len));
    // 若读取的字符总数>1024,则退出循环。
    if (total > 1024)
     break;
   } catch (ioexception e) {
    e.printstacktrace();
   }
  }

  try {
   in.close(); 
  } catch (ioexception e) { 
   e.printstacktrace(); 
  } 
 } 
}

sender.java的代码如下:

import java.io.ioexception; 

import java.io.pipedwriter; 
@suppresswarnings("all")
/** 
 * 发送者线程 
 */ 
public class sender extends thread { 

 // 管道输出流对象。
 // 它和“管道输入流(pipedreader)”对象绑定,
 // 从而可以将数据发送给“管道输入流”的数据,然后用户可以从“管道输入流”读取数据。
 private pipedwriter out = new pipedwriter();

 // 获得“管道输出流”对象
 public pipedwriter getwriter(){
  return out;
 } 

 @override
 public void run(){ 
  writeshortmessage();
  //writelongmessage();
 } 

 // 向“管道输出流”中写入一则较简短的消息:"this is a short message" 
 private void writeshortmessage() {
  string strinfo = "this is a short message" ;
  try {
   out.write(strinfo.tochararray());
   out.close(); 
  } catch (ioexception e) { 
   e.printstacktrace(); 
  } 
 }
 // 向“管道输出流”中写入一则较长的消息
 private void writelongmessage() {
  stringbuilder sb = new stringbuilder();
  // 通过for循环写入1020个字符
  for (int i=0; i<102; i++)
   sb.append("0123456789");
  // 再写入26个字符。
  sb.append("abcdefghijklmnopqrstuvwxyz");
  // str的总长度是1020+26=1046个字符
  string str = sb.tostring();
  try {
   // 将1046个字符写入到“管道输出流”中
   out.write(str);
   out.close();
  } catch (ioexception e) {
   e.printstacktrace();
  }
 }
}

pipetest.java的代码如下:

import java.io.pipedreader;
import java.io.pipedwriter;
import java.io.ioexception;

@suppresswarnings("all") 
/** 
 * 管道输入流和管道输出流的交互程序
 */ 
public class pipetest { 

 public static void main(string[] args) { 
  sender t1 = new sender(); 

  receiver t2 = new receiver(); 

  pipedwriter out = t1.getwriter(); 

  pipedreader in = t2.getreader(); 

  try { 
   //管道连接。下面2句话的本质是一样。
   //out.connect(in); 
   in.connect(out); 

   /** 
    * thread类的start方法: 
    * 使该线程开始执行;java 虚拟机调用该线程的 run 方法。 
    * 结果是两个线程并发地运行;当前线程(从调用返回给 start 方法)和另一个线程(执行其 run 方法)。 
    * 多次启动一个线程是非法的。特别是当线程已经结束执行后,不能再重新启动。 
    */
   t1.start();
   t2.start();
  } catch (ioexception e) {
   e.printstacktrace();
  }
 }
}

运行结果:
this is a short message
结果说明:

(1)

 in.connect(out);

它的作用是将“管道输入流”和“管道输出流”关联起来。查看pipedwriter.java和pipedreader.java中connect()的源码;我们知道 out.connect(in); 等价于 in.connect(out);
(2)

t1.start(); // 启动“sender”线程
t2.start(); // 启动“receiver”线程

先查看sender.java的源码,线程启动后执行run()函数;在sender.java的run()中,调用writeshortmessage();
writeshortmessage();的作用就是向“管道输出流”中写入数据"this is a short message" ;这条数据会被“管道输入流”接收到。下面看看这是如何实现的。
先看write(char char的源码。pipedwriter.java继承于writer.java;writer.java中write(char c[])的源码如下:

public void write(char cbuf[]) throws ioexception {
 write(cbuf, 0, cbuf.length);
}


实际上write(char c[])是调用的pipedwriter.java中的write(char c[], int off, int len)函数。查看write(char c[], int off, int len)的源码,我们发现:它会调用 sink.receive(cbuf, off, len); 进一步查看receive(char c[], int off, int len)的定义,我们知道sink.receive(cbuf, off, len)的作用就是:将“管道输出流”中的数据保存到“管道输入流”的缓冲中。而“管道输入流”的缓冲区buffer的默认大小是1024个字符。
至此,我们知道:t1.start()启动sender线程,而sender线程会将数据"this is a short message"写入到“管道输出流”;而“管道输出流”又会将该数据传输给“管道输入流”,即而保存在“管道输入流”的缓冲中。
接下来,我们看看“用户如何从‘管道输入流'的缓冲中读取数据”。这实际上就是receiver线程的动作。
t2.start() 会启动receiver线程,从而执行receiver.java的run()函数。查看receiver.java的源码,我们知道run()调用了readmessageonce()。
而readmessageonce()就是调用in.read(buf)从“管道输入流in”中读取数据,并保存到buf中。
通过上面的分析,我们已经知道“管道输入流in”的缓冲中的数据是"this is a short message";因此,buf的数据就是"this is a short message"。
为了加深对管道的理解。我们接着进行下面两个小试验。
试验一:修改sender.java

public void run(){ 
 writeshortmessage();
 //writelongmessage();
}

修改为

public void run(){ 
 //writeshortmessage();
 writelongmessage();
}

运行程序。运行结果如下:

201662985535729.jpg (1196×272)

从中,我们看出,程序运行出错!抛出异常 java.io.ioexception: pipe closed
为什么会这样呢?
我分析一下程序流程。
(1) 在pipetest中,通过in.connect(out)将输入和输出管道连接起来;然后,启动两个线程。t1.start()启动了线程sender,t2.start()启动了线程receiver。
(2) sender线程启动后,通过writelongmessage()写入数据到“输出管道”,out.write(str.tochararray())共写入了1046个字符。而根据pipedwriter的源码,pipedwriter的write()函数会调用pipedreader的receive()函数。而观察pipedreader的receive()函数,我们知道,pipedreader会将接受的数据存储缓冲区。仔细观察receive()函数,有如下代码:

while (in == out) {
 if ((readside != null) && !readside.isalive()) {
  throw new ioexception("pipe broken");
 }
 /* full: kick any waiting readers */
 notifyall();
 try {
  wait(1000);
 } catch (interruptedexception ex) {
  throw new java.io.interruptedioexception();
 }
}

而in和out的初始值分别是in=-1, out=0;结合上面的while(in==out)。我们知道,它的含义就是,每往管道中写入一个字符,就达到了in==out这个条件。然后,就调用notifyall(),唤醒“读取管道的线程”。
也就是,每往管道中写入一个字符,都会阻塞式的等待其它线程读取。
然而,pipedreader的缓冲区的默认大小是1024!但是,此时要写入的数据却有1046!所以,一次性最多只能写入1024个字符。
(03) receiver线程启动后,会调用readmessageonce()读取管道输入流。读取1024个字符会,会调用close()关闭,管道。
由(02)和(03)的分析可知,sender要往管道写入1046个字符。其中,前1024个字符(缓冲区容量是1024)能正常写入,并且每写入一个就读取一个。当写入1025个字符时,依然是依次的调用pipedwriter.java中的write();然后,write()中调用pipedreader.java中的receive();在pipedreader.java中,最终又会调用到receive(int c)函数。 而此时,管道输入流已经被关闭,也就是closedbyreader为true,所以抛出throw new ioexception("pipe closed")。
我们对“试验一”继续进行修改,解决该问题。
试验二: 在“试验一”的基础上继续修改receiver.java 将

public void run(){ 
 readmessageonce() ;
 //readmessagecontinued() ;
}

修改为

public void run(){ 
 //readmessageonce() ;
 readmessagecontinued() ;
}

此时,程序能正常运行。运行结果为:

01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
012345678901234567890123456789abcd
efghijklmnopqrstuvwxyz

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网