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
RandomNumberGeneratorimplementing theRunnableinterface. - Inside
RandomNumberGeneratorclass: a. Override therun()method. b. Create aRandomobject 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 forSquareCalculatorpassing the number as an argument. v. If the number is odd, start a new thread forCubePrinterpassing the number as an argument. - Define a class
SquareCalculatorimplementing theRunnableinterface. - Inside
SquareCalculatorclass: 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
CubePrinterimplementing theRunnableinterface. - Inside
CubePrinterclass: 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
MultiThreadExampleclass: a. Define themainmethod. b. Create a new thread forRandomNumberGenerator. c. Start the thread. - End of the program.







