日期:2014-05-20 浏览次数:20816 次
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; public class Expriment { public Expriment() { } /** * Launch the application. */ public static void main(String[] args) { try { PipedInputStream pis = new PipedInputStream(1024); PipedOutputStream pos = new PipedOutputStream(pis); ReadThread rt = new ReadThread(pis); WriteThread wt = new WriteThread(pos); wt.start(); rt.start(); Thread.sleep(10000); wt.interrupt(); rt.interrupt(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } } class WriteThread extends Thread { public WriteThread(OutputStream outputStream) { this.outputStream = outputStream; } @Override public void run() { int count = 0; do { count++; try { outputStream.write(new String(count + ": Hello, world ! I'm a write thread.\n").getBytes()); sleep(250); } catch (IOException e) { e.printStackTrace(); break; } catch (InterruptedException e) { e.printStackTrace(); break; } } while(!interrupted()); } private OutputStream outputStream; } class ReadThread extends Thread { public ReadThread(InputStream inputStream) { this.inputStream = inputStream; } @Override public void run() { byte[] buffer = new byte[1024]; do { try { int readCount = inputStream.read(buffer, 0, 16); if (readCount > 0) { System.out.print(new String(buffer, 0, readCount)); } } catch (IOException e) { e.printStackTrace(); break; } } while(!interrupted()); } private InputStream inputStream; }