AdSense

AdSense3

Saturday 15 November 2014

PipedInputStream and PipedOutputStream classes

The PipedInputStream and PipedOutputStream classes can be used to read and write data simultaneously. Both streams are connected with each other using the connect() method of the PipedOutputStream class.


Example of PipedInputStream and PipedOutputStream classes using threads

Here, we have created two threads t1 and t2. The t1 thread writes the data using the PipedOutputStream object and the t2thread reads the data from that pipe using the PipedInputStream object. Both the piped stream object are connected with each other.
  1. import java.io.*;  
  2. class PipedWR{  
  3. public static void main(String args[])throws Exception{  
  4. final PipedOutputStream pout=new PipedOutputStream();  
  5. final PipedInputStream pin=new PipedInputStream();  
  6.   
  7. pout.connect(pin);//connecting the streams  
  8. //creating one thread t1 which writes the data  
  9. Thread t1=new Thread(){  
  10. public void run(){  
  11. for(int i=65;i<=90;i++){  
  12. try{  
  13. pout.write(i);  
  14. Thread.sleep(1000);  
  15. }catch(Exception e){}  
  16. }  
  17. }  
  18. };  
  19. //creating another thread t2 which reads the data  
  20. Thread t2=new Thread(){  
  21. public void run(){  
  22. try{   
  23. for(int i=65;i<=90;i++)  
  24. System.out.println(pin.read());  
  25. }catch(Exception e){}  
  26. }  
  27. };  
  28. //starting both threads  
  29. t1.start();  
  30. t2.start();  
  31. }}  

No comments:

Post a Comment