java线程通信

来源:互联网 发布:如何将域名转入万网 编辑:程序博客网 时间:2024/06/07 01:04
Code:
  1. import java.io.*;  
  2. public class PipedStream {  
  3.     public static void main(String[] args) {  
  4.         PipedInputStream pis = new PipedInputStream();  
  5.         PipedOutputStream pos = new PipedOutputStream();  
  6.         try{  
  7.             pos.connect(pis);  
  8.         }  
  9.         catch(Exception e) {  
  10.             e.printStackTrace();  
  11.         }     
  12.         Producer p = new Producer(pos);  
  13.         Consumer c = new Consumer(pis);  
  14.         Thread t1 = new Thread(p);  
  15.         t1.run();  
  16.         c.run();  
  17.     }  
  18. }  
  19.   
  20. class Producer implements Runnable {  
  21.     PipedOutputStream pos;  
  22.     Producer(PipedOutputStream pos) {  
  23.         this.pos = pos;  
  24.     }  
  25.       
  26.     public void run() {  
  27.         try{  
  28.             pos.write("welcome you!".getBytes());  
  29.         }catch(Exception e) {  
  30.             e.printStackTrace();  
  31.         }  
  32.     }  
  33. }  
  34. class Consumer extends Thread {  
  35.     PipedInputStream pis;  
  36.     Consumer(PipedInputStream pis) {  
  37.         this.pis = pis;  
  38.     }  
  39.     public void run() {  
  40.         byte[] buf = new byte[100];   
  41.         try{  
  42.             int length = pis.read(buf);  
  43.             System.out.println(new String(buf, 0, length));  
  44.         }  
  45.         catch(Exception e) {  
  46.             e.printStackTrace();  
  47.         }         
  48.     }  
  49. }  

 

原创粉丝点击