Write a program for the following: Create a thread named NumberThread to generate a random number. If the generated number is even create a thread SumThread which generate a set of random numbers and find the sum of all numbers. If the generated number is odd create another AvgThread that generate a set of random numbers and find the average of all numbers. Write a driver class to demonstrate the multithreading program.
Answers
Explanation:
s
public class Summing implements Runnable {
int a;
public Summing(int a) {
this.a = a;
}
public void run() {
addRondom();
}
public void addRondom() {
Random rand = new Random();
int n = rand.nextInt(10) + 1;
System.out.println("number generated: " + n);
synchronized (this) {
a += n;
}
}
}
and then
public static void main(String[] args) {
int base = 0;
Summing sum2 = new Summing(base);
Thread t1 = new Thread(sum2);
Thread t2 = new Thread(sum2);
Thread t3 = new Thread(sum2);
Thread t4 = new Thread(sum2);
Thread t5 = new Thread(sum2);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Answer:
I hope answer is helpful to us