任务间使用管道输入输出

管道流PipedReader和PipedWriter,它不同于普通的IO流,管道基本上是一个阻塞队列,且当线程对象调用shutdownNow之后,PipedReader是可中断的,而不通的IO是不可中断的。

 

==============向管道写任务==============

public class Sender implements Runnable{

 private Random random=new Random(47);
 
 private PipedWriter out=new PipedWriter();
 
 public PipedWriter getPipedWriter(){
  return out;
 }
 
 
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  try {
   while(true){
    for(char c='A';c<='z';c++){
     out.write(c);
     System.out.println("Write:"+c);
     TimeUnit.MILLISECONDS.sleep(random.nextInt(500));
    }
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   System.out.println("Sender writer exception");
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   System.out.println("Sender interrupted.");
  }
  
 }
}

 

 

======================从管道读取任务

public class Receiver implements Runnable{

 private PipedReader in;
 
 public Receiver(Sender sender) {
  // TODO Auto-generated constructor stub
  try {
   in=new PipedReader(sender.getPipedWriter());
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 @Override
 public void run() {
  // TODO Auto-generated method stub
  try {
   while(true){
    System.out.println("Read:"+(char)in.read());
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

 

======================测试类

public class PipedIO {

 public static void main(String[] args) throws InterruptedException{
  Sender sender=new Sender();
  Receiver receiver=new Receiver(sender);
  ExecutorService exec=Executors.newCachedThreadPool();
  exec.execute(sender);
  exec.execute(receiver);
  TimeUnit.SECONDS.sleep(4);
  exec.shutdownNow();
  
 }
}

 

----------------执行结果如下:

Read:A
Write:A
Write:B
Write:C
Write:D
Write:E
Read:B
Read:C
Read:D
Read:E
Write:F
Write:G
Read:F
Read:G
Write:H
Write:I
Write:J
Write:K
Write:L
Write:M
Read:H
Read:I
Read:J
Read:K
Read:L
Read:M
Write:N
Write:O
Write:P
Write:Q
java.io.InterruptedIOException
Read:N
Read:O
Read:P
Read:Q
Sender interrupted.
 at java.io.PipedReader.read(PipedReader.java:242)
 at com.test.thread.pipe.Receiver.run(Receiver.java:24)
 at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
 at java.lang.Thread.run(Thread.java:619)

你可能感兴趣的:(thread,管道流,PipedReader)