Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at a Java program to demonstrate Inter-Thread Communication. I would suggest you go through the below link before proceeding with this post.
Core Java program to create multiple threads
Inter-Thread communication is an important aspect in a multi-threaded environment. Java provides this facility using below three methods defined in Object class:
- wait(): Immediately releases the lock on the object and waits for acquiring the lock
- notify(): Notifies the waiting Thread and releases the lock(may not release the lock immediately)
- notifyAll(): Notifies the all waiting Threads and releases the lock(may not release the lock immediately)
We will consider a scenario where there are three Threads in which one will generate a random number every second. The second thread prints its square value if the random number is an even number. The third thread will print the cube value if the random number is an odd number.
Here is the simple random number generator class:
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 |
package com.clearurdoubt.threads; /** * * @author Sai Gowtham Badvity * A simple random number generator * */ public class RandomNumberGenerator { int randomnumber; boolean isReady; public int getRandomnumber() { return randomnumber; } /** * Method to generate a random number */ public void generateRandomnumber() { this.randomnumber = (int)(Math.random()*1000); } } |
Let’s look at the program for implementing the above-mentioned scenario:
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
package com.clearurdoubt.threads; /** * * @author Sai Gowtham Badvity * Demo program for illustrating the Inter Thread Communication * */ public class InterThreadCommunication { static boolean isReadyForReading = false; // variable for checking whether the value is ready for reading static boolean isGeneratorDone = false; // variable for checking whether Random Number generation is completed. public static void main(String[] args) throws InterruptedException { RandomNumberGenerator randomGenerator = new RandomNumberGenerator(); // Random Number Generator instantiation // New Thread for printing Squares if the random number is even Thread printSquares = new Thread(new Runnable() { public void run() { synchronized(randomGenerator) // Entering into synchronized block { try { while(!isGeneratorDone) // Loop for keeping the Thread alive { randomGenerator.wait(2000); // Wait for maximum 2 seconds for generator Thread to generate a random number if(isReadyForReading) // current random number is ready for getting read { if(randomGenerator.getRandomnumber() % 2 == 0) // if it is even number { // Print the Square of the current random number String str = randomGenerator.getRandomnumber() + "*" + randomGenerator.getRandomnumber(); System.out.println(Thread.currentThread().getName() + " printing " + str + "=" + randomGenerator.getRandomnumber() * randomGenerator.getRandomnumber()); // Square of the number is printed so set "isReadyForReading=false" isReadyForReading = false; } } //processing the current number is done. Notify all the waiting threads. randomGenerator.notifyAll(); } } catch (InterruptedException e) { e.printStackTrace(); } } } },"Square Printer"); // New Thread for printing Cubes if the random number is odd Thread printCubes = new Thread(new Runnable() { public void run() { synchronized(randomGenerator) // Entering into synchronized block { try { while(!isGeneratorDone) // Loop for keeping the Thread alive { randomGenerator.wait(2000); // Wait for maximum 2 seconds for generator Thread to generate a random number if(isReadyForReading) // current random number is ready for getting read { if(randomGenerator.getRandomnumber() % 2 == 1) // if it is odd number { // Print the Cube of the current random number String str = randomGenerator.getRandomnumber() + "*" + randomGenerator.getRandomnumber() + "*" + randomGenerator.getRandomnumber() ; System.out.println(Thread.currentThread().getName() + " printing " + str + "=" + randomGenerator.getRandomnumber() * randomGenerator.getRandomnumber() * randomGenerator.getRandomnumber()); // Cube of the number is printed so set "isReadyForReading=false" isReadyForReading = false; } } //processing the current number is done. Notify all the waiting threads. randomGenerator.notifyAll(); } } catch (InterruptedException e) { e.printStackTrace(); } } } },"Cube Printer"); // New Thread for generating a random number for every 1 second Thread generator = new Thread(new Runnable() { public void run() { try { synchronized(randomGenerator) // Entering into synchronized block { System.out.println("Starting the Random Number generation."); int i = 1; while(isGeneratorDone || i <= 10) // Loop for generating random number for 10 times { Thread.sleep(1000); if(!isReadyForReading) { // isReadyForReading=false that means we need to generate a random number randomGenerator.generateRandomnumber(); System.out.println(); System.out.println(i + " Random Number generated : " + randomGenerator.getRandomnumber()); i++; // increment i isReadyForReading = true; // random number generated and it is ready for getting read. randomGenerator.notifyAll(); // Notify all the waiting threads } else { // isReadyForReading=true that means generator needs to wait till the current random number gets processed randomGenerator.wait(); } } isGeneratorDone=true; // 10 random numbers were generated so set the value to true. randomGenerator.notifyAll(); // Notify all waiting threads. } } catch (InterruptedException e) { e.printStackTrace(); } } },"Generator"); System.out.println("Java program for demonstrating the Inter Thread Communication"); System.out.println(); // Start the Threads generator.start(); printSquares.start(); printCubes.start(); // Wait for the Threads to get completed generator.join(); printSquares.join(); printCubes.join(); System.out.println(); System.out.println("Completed the Random Number generation."); } } |
Output:
If the Random number is even, it’s square is printed by Square Printer thread and if it is odd, it’s cube is printed by Cube Printer thread. The inter-thread communication is dependent on how we call wait(), notify() and notifyAll() to proceed with the execution.
Happy Learning :).
Please leave a reply in case of any queries.