本文共 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/