8 9 10 11 private int maxNumber; 12 private boolean isEvenNumber; 13 14 public NumberWriter(PipedWriter writer, int maxNumber, boolean isEvenNumber) { 15 this.writer = writer; this.maxNumber = maxNumber; 16 this.isEvenNumber = isEvenNumber; 17 } 18 19 public void run() { 20 int i = 1; while (i <= maxNumber) { 21 try { 22 if (isEvenNumber && (i % 2) == 0) { 23 writer.write(i); 24 } else if (!isEvenNumber && i%2 != 0) { 25 writer.write(i); } 26 ++i; 27 } catch (IOException e) { 28 e.printStackTrace(); 29 } 30 } } 31 32 public static void main(String[] args) { 33 final int MAX_NUM = 10; 34 35 PipedWriter oddNumberWriter = new PipedWriter(); 36 PipedWriter evenNumberWriter = new PipedWriter(); 37 NumberWriter oddGen = new NumberWriter(oddNumberWriter, MAX_NUM, false); 38 NumberWriter evenGen = new NumberWriter(evenNumberWriter, MAX_NUM, true); 39 NumberReceiver receiver = new NumberReceiver(oddNumberWriter, evenNumberWriter); 40 41 42 evenGen.start(); 43 receiver.start(); 44 } 45 46 } 47 48 49 50 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; 1 2 import java.io.IOException; 3 import java.io.PipedReader; 4 import java.io.PipedWriter;
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 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); 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. 1 2 3 4 package multithreading; import java.io.IOException; import java.io.PipedReader; import java.io.PipedWriter;
Java%20Multi-Threading%20Questions%20Answers.docx