Solve the following using java
Write a program that runs three threads, each thread randomizes a
number between 1 and 100. The main thread waits for all the others
to finish, calculates the maximum of the numbers, which were
randomized, and prints it.
Random number 1: 10
Random number 2: 38
Random number 3: 81
Max: 81
Note: You should create 3 threads in adition to the main thread. Also, you can use a single thread class and create 3 instances from it in the main class.
If you have any problem with the code feel free to comment.
Program
//custom Random class for generating random number between 1 and
100;
class Random {
int num;
public void randomize() {
num = (int) (Math.random() * 100 +
1);
}
}
public class Test {
public static void main(String[] args) throws
InterruptedException {
int num1, num2, num3;
// object of random
Random obj = new Random();
// creating 3 threads
// each thread calling
randomize()
Thread th1 = new Thread(() ->
{
obj.randomize();
});
Thread th2 = new Thread(() ->
{
obj.randomize();
});
Thread th3 = new Thread(() ->
{
obj.randomize();
});
// starting and waiting for each
thread to finish
// then assigning the value to
num's
th1.start();
th1.join();
num1 = obj.num;
th2.start();
th2.join();
num2 = obj.num;
th3.start();
th3.join();
num3 = obj.num;
// printing each thread
result
System.out.println("Random Number
1: " + num1);
System.out.println("Random Number
2: " + num2);
System.out.println("Random Number
3: " + num3);
// fidning maximum number
int max = (num1 > num2
&& num1 > num3) ? num1 : (num2 > num1 && num2
> num3) ? num2 : num3;
// printing maximum number
System.out.println("Max: " +
max);
}
}
Output
Get Answers For Free
Most questions answered within 1 hours.