Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Beginner
Jun 1, 1999

Running Piped Threads

In a typical application using piped streams, an object of type PipedInputStream and an object of type PipedOutputStream are started as separate threads. One thread uses a PipedOutputStream to output data. The other thread uses a PipedInputStream to read in data. The two streams are connected through a connect() call used on either stream. To find out how to instantiate piped streams in separate threads, see the tip "Threading Piped Streams."

Each thread has a run() method, which is typical of a Java thread. In the case of an application using piped streams, these run() methods are interdependent. These code excerpts illustrate the run() methods for a PipedInputStream ("in_") and a PipedOutputStream ("out_"). Assume that these two have already been "connected." One thread reads input from the standard input and writes it to the PipedOutStream. The other thread reads in the data from the PipedInputStream (which is connected to the PipedOutputStream), capitalizes all the letters, and writes it out to the standard output stream.

This code excerpt shows the run() method for the thread that uses the PipedOutputStream "out_".

 
1.      public void run () {
2.        try {
3.          while (true) {
4.           byte[] outArray = new byte[10];
5.           System.in.read(outArray, 0, 10);
6.           out_.write(outArray, 0,10);
7.         }
8.        }
9.        catch (Exception e) { e.printStackTrace(); }
10. }
The run method has a while loop. On Lines 4-5, the method reads data in batches of 10 bytes from the standard input stream. This data is written out to the PipedOutputStream out_ on Line 6.

The run() method for a thread using a PipedInputStream "in_" is as follows:

 
1.      public void run () {
2.        try {
3.          while (true) {
4.          byte[] inArray = new byte[10];
5.          in_.read(inArray, 0, 10);
6.          System.out.print((new String(inArray)).toUpperCase());
7.          }
8.      }
9.        catch (Exception e) { e.printStackTrace(); }
10. }
The run method has a while loop similar to the one for PipedOutputThread. On Lines 4-5, the method reads data in batches of 10 bytes from the PipedInputStream pins. This data is written out to the standard output on Line 6.

To view the code that calls these run() methods, see the Tip "Threading Piped Streams."

Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap