博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
任务间使用管道进行输入/输出
阅读量:4230 次
发布时间:2019-05-26

本文共 1756 字,大约阅读时间需要 5 分钟。

通过PipedWriter类小姑娘管道中写数据

PipedReader类允许不同任务从同一管道中读取数据,如果当前没有数据就阻塞,等待数据的到来。

并且PiPedReader 类与普通I/O之间有重要的差异,可以被中断。

class Sender implements Runnable{    private Random rand=new Random(47);    private PipedWriter out=new PipedWriter();    public PipedWriter getOut() {        return out;    }    @Override    public void run() {        try {            while(true){                for(char c='A';c<='z';c++){                    out.write(c);                    TimeUnit.MILLISECONDS.sleep(rand.nextInt(500));                }            }        } catch (IOException e) {            System.out.println(e+" Sender write excetption");        } catch (InterruptedException e) {            System.out.println(e+" Sender sleep interrupted");        }    }}class Receiver implements Runnable{    private PipedReader in;    public Receiver(Sender sender) throws IOException{        in=new PipedReader(sender.getOut());    }    @Override    public void run() {        try {            while(true){                System.out.println("Read: "+(char)in.read()+" ");            }        } catch (IOException e) {            System.out.println(e+" Receiver read exception");        }    }}public class PipedIO {    public static void main(String[] args)throws Exception{        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
Read: B
Read: C
Read: D
Read: E
Read: F
Read: G
Read: H
Read: I
Read: J
Read: K
Read: L
Read: M
java.lang.InterruptedException: sleep interrupted Sender sleep interrupted
java.io.InterruptedIOException Receiver read exception

转载地址:http://wojqi.baihongyu.com/

你可能感兴趣的文章
Information Systems : Achieving Success by Avoiding Failure
查看>>
Web Systems Design and Online Consumer Behavior
查看>>
VoIP For Dummies
查看>>
Administrator's Guide to SQL Server 2005
查看>>
Ajax Design Patterns
查看>>
DNS and BIND (5th Edition)
查看>>
Firewall Fundamentals
查看>>
Learning PHP and MySQL
查看>>
Agile Software Construction
查看>>
Computer Security Basics
查看>>
Sams Teach Yourself MySQL in 10 Minutes
查看>>
Information Systems : The State of the Field
查看>>
IPv6 Essentials
查看>>
Microsoft Visual C++ 2005 Express Edition Programming for the Absolute Beginner
查看>>
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
查看>>
Pro .NET 2.0 Windows Forms and Custom Controls in C#
查看>>
Beginning Regular Expressions
查看>>
Beginning Visual Web Developer 2005 Express: From Novice to Professional
查看>>
Beginning Programming
查看>>
Windows .NET Server 2003 Domains & Active Directory
查看>>