Write a multi-threaded Java program in which, one thread generates odd numbers and write to a pipe and the second thread generates even numbers and write to another pipe, and a third thread receives the numbers from both the pipes and evaluates if the sum is multiples of 5

In Unix, a pipe (“|”) operator helps you to redirect output from one command to another.

PipedReader and PipedWriterclasses in java.io package helps you to do the same.

It helps you to redirect the read input into writer seamlessly.

In Unix, two different processes on different address spaces can communicate using pipe, but in java two threads on the JVM can communicate using Piped ByteStream/CharacterStream within the same process

(i.e same address space)

 

 

 

Here is the code snippet. The Writer threads responsible for writing odd and even numbers to the respective pipes.

package multithreading;

 

import java.io.IOException;

import java.io.PipedWriter;

 

public class NumberWriter extends Thread {

 

private PipedWriter writer;

private int maxNumber;

private boolean isEvenNumber;

 

public NumberWriter(PipedWriter writer, int maxNumber, boolean isEvenNumber) {

this.writer = writer;

this.maxNumber = maxNumber;

this.isEvenNumber = isEvenNumber;

}

 

public void run() {

int i = 1;

while (i <= maxNumber) {

try {

if (isEvenNumber && (i % 2) == 0) {

writer.write(i);

} else if (!isEvenNumber && i%2 != 0) {

writer.write(i);

}

++i;

} catch (IOException e) {

e.printStackTrace();

}

}

}

 

public static void main(String[] args) {

final int MAX_NUM = 10;

 

PipedWriter oddNumberWriter = new PipedWriter();

PipedWriter evenNumberWriter = new PipedWriter();

 

NumberWriter oddGen = new NumberWriter(oddNumberWriter, MAX_NUM, false);

NumberWriter evenGen = new NumberWriter(evenNumberWriter, MAX_NUM, true);

NumberReceiver receiver = new NumberReceiver(oddNumberWriter, evenNumberWriter);

 

oddGen.start();

evenGen.start();

receiver.start();

 

}

 

}

 

 

The receiver thread that listens to both odd and even number pipes and computes the sum. If the sum is a multiple of 5, it prints the numbers and the sum.

package multithreading;

 

import java.io.IOException;

import java.io.PipedReader;

import java.io.PipedWriter;

 

public class NumberReceiver extends Thread {

 

private PipedReader oddReader;

private PipedReader evenReader;

 

public NumberReceiver(PipedWriter oddWriter, PipedWriter evenWriter) {

try {

this.oddReader = new PipedReader(oddWriter);

this.evenReader = new PipedReader(evenWriter);

} catch (IOException e) {

e.printStackTrace();

}

}

 

public void run() {

int odd =0, even=0;

 

try {

while (odd != -1) {

odd = oddReader.read();

even = evenReader.read();

 

if ((odd + even) % 5 == 0) {

System.out.println(“match found ” + odd + ” + ” + even + ” = ” + (odd + even));

}

}

 

} catch (IOException e) {

System.exit(1);

}

 

 

}

}

The output will be something like:

match found 7 + 8 = 15