In: Computer Science
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
// Threads.java
public class Threads {
public static void main(String[] args) throws Exception {
// number of throws
int numThrows = 100000;
// a shared array of numThrows size to store the thrown die rolls
int sharedArray[] = new int[numThrows];
// creating a DieRollThread, passing the array, 0 as start index, middle
// index of sharedArray as end index (first half of the array)
DieRollThread t1 = new DieRollThread(sharedArray, 0, numThrows / 2);
// creating another DieRollThread to store the die rolls in second half
// of the array
DieRollThread t2 = new DieRollThread(sharedArray, (numThrows / 2) + 1,
numThrows - 1);
// starting both threads
t1.start();
t2.start();
// waiting for both threads to finish execution
t1.join();
t2.join();
// creating an array to store the frequencies of each number. index 0
// represents frequency of 1, index 5 represents frequency of 6 etc.
int frequencies[] = new int[6];
for (int i = 0; i < sharedArray.length; i++) {
// getting value of die at index i
int dieValue = sharedArray[i];
// incrementing the counter at dieValue-1 index
frequencies[dieValue - 1]++;
}
System.out.println("Frequencies of each number thrown:");
int sum = 0;
// now looping and printing frequency of each number
for (int i = 0; i < frequencies.length; i++) {
System.out.println((i + 1) + ": " + frequencies[i]);
// summing the frequencies so that we can verify it with numRolls
sum += frequencies[i];
}
// if everything is correct, sum of frequencies will be equal to
// numThrows
System.out.println("Total throws: " + sum);
}
}
// a class extending Thread class that performs rolling a die and storing the
// drawn number in an array at specified positions, should be placed within Threads.java file
class DieRollThread extends Thread {
// reference to the array
int[] array;
// start and end index of segments alloted to this thread
int startIndex, endIndex;
// constructor receiving reference to the array, start and end index
public DieRollThread(int[] array, int startIndex, int endIndex) {
this.array = array;
this.startIndex = startIndex;
this.endIndex = endIndex;
}
@Override
public void run() {
// looping from i=startIndex to i=endIndex
for (int i = startIndex; i <= endIndex; i++) {
// generating a random number between 1 and 6
int die = (int) (Math.random() * 6) + 1;
// adding to the array at index i
array[i] = die;
}
}
}
/*OUTPUT*/
Frequencies of each number thrown:
1: 16822
2: 16708
3: 16530
4: 16890
5: 16565
6: 16485
Total throws: 100000