Write a java program that implements a multi-thread application that has three threads. First thread generates a random integer every 1 second and if the value is even, the second thread computes the square of the number and prints. If the value is odd, the third thread will print the value of the cube of the number.
CODE:
import java.util.Random;
class RandomNumberGenerator implements Runnable {
public void run() {
Random random = new Random();
while (true) {
try {
Thread.sleep(1000); // Sleep for 1 second
int number = random.nextInt(100); // Generate a random integer between 0 and 99
System.out.println("Generated number: " + number);
if (number % 2 == 0) {
Thread thread = new Thread(new SquareCalculator(number));
thread.start();
} else {
Thread thread = new Thread(new CubePrinter(number));
thread.start();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SquareCalculator implements Runnable {
private int number;
public SquareCalculator(int number) {
this.number = number;
}
public void run() {
System.out.println("Square of " + number + " is: " + (number * number));
}
}
class CubePrinter implements Runnable {
private int number;
public CubePrinter(int number) {
this.number = number;
}
public void run() {
System.out.println("Cube of " + number + " is: " + (number * number * number));
}
}
public class MultiThreadExample {
public static void main(String[] args) {
Thread thread = new Thread(new RandomNumberGenerator());
thread.start();
}
}
- Define a class
RandomNumberGenerator
implementing theRunnable
interface. - Inside
RandomNumberGenerator
class: a. Override therun()
method. b. Create aRandom
object to generate random numbers. c. Inside an infinite loop: i. Sleep the thread for 1 second. ii. Generate a random integer between 0 and 99. iii. Print the generated number. iv. If the number is even, start a new thread forSquareCalculator
passing the number as an argument. v. If the number is odd, start a new thread forCubePrinter
passing the number as an argument. - Define a class
SquareCalculator
implementing theRunnable
interface. - Inside
SquareCalculator
class: a. Define a private variablenumber
. b. Define a constructor to initialize thenumber
. c. Override therun()
method. d. Print the square of thenumber
. - Define a class
CubePrinter
implementing theRunnable
interface. - Inside
CubePrinter
class: a. Define a private variablenumber
. b. Define a constructor to initialize thenumber
. c. Override therun()
method. d. Print the cube of thenumber
. - Define a class
MultiThreadExample
. - Inside
MultiThreadExample
class: a. Define themain
method. b. Create a new thread forRandomNumberGenerator
. c. Start the thread. - End of the program.