24 25 26 27 } 28 29 public static void main(String[] args) { 30 NumberUtility numUtility = new NumberUtility(); //single instance shared by oddGen 31 final int MAX_NUM = 10; 32 33 //create 2 threads, one to generate odd numbers and the other to generate even 34 NumberGenerator oddGen = new NumberGenerator(numUtility, MAX_NUM, false); NumberGenerator evenGen = new NumberGenerator(numUtility, MAX_NUM, true); 35 36 //start the thread - invokes the run() method on NumberGenerator 37 evenGen.start(); //start the thread - invokes the run() method on NumberGenerator 38 39 } 40 41 } 42 43 44 Next, create the utility that is used for communicating between the two threads with wait() and notifyAll() methods via synchronized methods. package multithreading; 1 2 import static java.lang.System.out; 3 4 public class NumberUtility { 5 6 boolean oddPrinted = false; 7 8 public synchronized void printOdd(int number) { 9 10 (oddPrinted == true) { try { 11 wait(); // waits until notified by even thread 12 13 } catch (InterruptedException e) { 14 e.printStackTrace(); 15 } } 16 17 out.println("printOdd() " + number); 18 oddPrinted = true; 19 notifyAll(); //notify all waiting threads 20 21 } 22 23 public synchronized void printEven(int number) { while (oddPrinted == false) { 24 try { 25 wait(); //waits until notified by the odd thread 26 27 } catch (InterruptedException e) {
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 } public static void main(String[] args) { NumberUtility numUtility = new NumberUtility(); //single instance shared by oddGen final int MAX_NUM = 10; //create 2 threads, one to generate odd numbers and the other to generate even NumberGenerator oddGen = new NumberGenerator(numUtility, MAX_NUM, false); NumberGenerator evenGen = new NumberGenerator(numUtility, MAX_NUM, true); //start the thread - invokes the run() method on NumberGenerator evenGen.start(); //start the thread - invokes the run() method on NumberGenerator } } Next, create the utility that is used for communicating between the two threads with wait() and notifyAll() methods via synchronized methods. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 package multithreading; import static java.lang.System.out; public class NumberUtility { boolean oddPrinted = false; public synchronized void printOdd(int number) { (oddPrinted == true) { try { wait(); // waits until notified by even thread } catch (InterruptedException e) { e.printStackTrace(); } } out.println("printOdd() " + number); oddPrinted = true; notifyAll(); //notify all waiting threads } public synchronized void printEven(int number) { while (oddPrinted == false) { try { wait(); //waits until notified by the odd thread } catch (InterruptedException e) {
Java%20Multi-Threading%20Questions%20Answers.docx