devxlogo

Passing Data Between Two Threads

Passing Data Between Two Threads

Question:
I am new to Java and am currently trying toassociate idioms and techniques from otherlanguages/environments with like capabilities inJava. Specifically, I am trying to determine howto perform inter-thread and inter-processcommunication. How does one pass data, in theform of an Object or Object reference, betweentwo threads?

Answer:
Assume that the Object(data) beingcommunicated is private to the sending class/packageand not within the scope of the receiving class/package,although the definition of the Object being passedis known to the receiving class/package.

Can this type of communication be performedusing Piped Streams?

One advantage of threads over processes isthat because threads share an address space, sharedmemory communication is fairly easy to set up, providedyou synchronize access to shared data.

Java also provides the classes PipedInputStream andPipedOutputStream specifically for message passingstyle communication between threads. In the examplebelow, I create a pipeline of four threads:

generator ->filter -> amplifier -> accumulator 
Each arrow (->) represents a PipedOutputStream tothe thread on the left, and a PipedInputStream tothe thread on the right. Generator fills itsoutput pipe with integers from 1 to 100. Filterreads from its input stream, and places only eveninputs into its output stream. Amplifier readsnumbers from its input stream, and places theirsquares in its output stream. Finally, accumulatoraccumulates the sum of all inputs from its inputstream.
*/import java.io.*;// Generators fill output pipe with ints from first to lastclass Generator extends Thread {   private DataOutputStream dout;   private int first, last;   public Generator(PipedOutputStream out, int start, int end) {      // filter pipes into data streams      dout = new DataOutputStream(out);      first = start;      last = end;   }   public void run() {      for(int i = first; i 

devx-admin

Share the Post: