介绍:不同的数据源之间通过建立管道进行数据通信。如图:
线程之间通信最好的方式就是采用管道机制,类似水管一样,水管可以对接,组合成各种具有过滤性质的管道,管道和线程灵活使用,可以提高效率。(Channel)信道复用机制。
class Recever implements Runnable { PipedInputStream inputStream; Recever(PipedInputStream inputStream) { this.inputStream = inputStream; } @Override public void run() { try { while (true) { byte[] buffers = new byte[512]; int len = inputStream.read(buffers); String s = new String(buffers, 0, len); System.out.println("收到:" + s); } // inputStream.close(); } catch (Exception e) { } } }
class Sender implements Runnable { PipedOutputStream outputStream; Sender(PipedOutputStream outputStream) { this.outputStream = outputStream; } @Override public void run() { try { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String msg = scanner.nextLine(); outputStream.write(msg.getBytes()); outputStream.flush(); } } catch (Exception e) { e.printStackTrace(); } } }
public static void main(String[] args) throws InterruptedException, IOException { PipedInputStream in = new PipedInputStream(); PipedOutputStream out = new PipedOutputStream(); in.connect(out); new Thread(new Recever(in)).start(); new Thread(new Sender(out)).start(); }
//数据流的合并-读取几个文件的内容输入到下一个文件
InputStream in1 = new FileInputStream("c:/a1.txt"); InputStream in2 = new FileInputStream("c:/a2.txt"); InputStream in3 = new FileInputStream("c:/a3.txt"); Vector<InputStream> inputStreams = new Vector<InputStream>(); inputStreams.add(in1); inputStreams.add(in2); inputStreams.add(in3); Enumeration<? extends InputStream> enumeration = inputStreams.elements(); SequenceInputStream inputStream = new SequenceInputStream(enumeration ); OutputStream os = new FileOutputStream("c:/a4.txt"); byte[] buffer = new byte[512]; int length = -1; while((length = inputStream.read(buffer))!=-1){ os.write(buffer, 0, length); os.flush(); } os.close(); inputStream.close();
//内存读取
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); arrayOutputStream.write("test".getBytes()); arrayOutputStream.flush(); byte[] buffer = arrayOutputStream.toByteArray(); ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(buffer );