Question

In: Computer Science

java language question Write a program that employs 2 threads that each toss their own die...

java language question

Write a program that employs 2 threads that each toss their own die (modelled by a random number generator that generates random numbers in the range 1..6) a given number of times. In both cases the result of each toss is stored in a shared array. The array is deemed to be large enough to store the result of every throw and each thread should only write to its own array segment. Once the threads have completed their work then the main program counts the frequency of each number thrown and prints it on the screen.

Solutions

Expert Solution

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


Related Solutions

DO THIS IN JAVA Write a complete Java program. the program has two threads. One thread...
DO THIS IN JAVA Write a complete Java program. the program has two threads. One thread prints all capital letters 'A' to'Z'. The other thread prints all odd numbers from 1 to 21.
IN C LANGUAGE: Write a multi-threaded Linux program that synchronizes it's threads to write to a...
IN C LANGUAGE: Write a multi-threaded Linux program that synchronizes it's threads to write to a file without the file becoming corrupted. To do this, your program will create three threads which write strings to the same file. Each thread will randomly write a selection of strings to the file at random intervals. When finished, the file will contain all the strings written correctly to the file. You may use mutexes, semaphores, or a monitor your write on your own....
In this question, you are asked to write a simple java program to understand natural language....
In this question, you are asked to write a simple java program to understand natural language. The user will enter the input following the format: Name came to City, Country in Year. For example: Robin came to Montreal, Canada in 2009. Assume a perfect user will follow the exactly above formats for the inputs. Your program should be able to analyze the key words (Name, City, Country and Year) from the inputs and reorganize the outputs following format: Name stay...
Write a program (in C, or Java, or C++, or C#) that creates three new threads...
Write a program (in C, or Java, or C++, or C#) that creates three new threads (besides the already existing main thread) and synchronizes them in such a way that each thread displays it's thread id in turn for 5 iterations. The output of the program should look like this: Thread 1 - iteration no. 1 Thread 2 - iteration no. 1 Thread 3 - iteration no. 1 Thread 1 - iteration no. 2 Thread 2 - iteration no. 2...
In C++  Write a program that simulates coin tossing. For each toss of the coin the program...
In C++  Write a program that simulates coin tossing. For each toss of the coin the program should print heads or tails. Let the program toss the coin 100 times and count the number times each side of the coin appears. Print the results. 0 represents tails and 1 for heads.
***Please answer the question using the JAVA programming language. Write a program that calculates mileage reimbursement...
***Please answer the question using the JAVA programming language. Write a program that calculates mileage reimbursement for a salesperson at a rate of $0.35 per mile. Your program should interact (ask the user to enter the data) with the user in this manner: MILEAGE REIMBURSEMENT CALCULATOR Enter beginning odometer reading > 13505.2 Enter ending odometer reading > 13810.6 You traveled 305.4 miles. At $0.35 per mile, your reimbursement is $106.89. ** Extra credit 6 points: Format the answer (2 points),...
Language is Java Design and write a Java console program to estimate the number of syllables...
Language is Java Design and write a Java console program to estimate the number of syllables in an English word. Assume that the number of syllables is determined by vowels as follows. Each sequence of adjacent vowels (a, e, i, o, u, or y), except for a terminal e, is a syllable. However, the minimum number of syllables in an English word is one. The program should prompt for a word and respond with the estimated number of syllables in...
JAVA LANGUAGE Write a program that declares a 2-Dimensional Array with 4 rows and 4 columns...
JAVA LANGUAGE Write a program that declares a 2-Dimensional Array with 4 rows and 4 columns to store integer values, and then: fill elements with values as the sum of its column index and row index, e.g., the element at row index 0 and column index 0 is (0+0=0), the element at row index 0 and column index 1 is (0+1=1). compute the sum of elements at the second row. compute the sum of elements at the third column. compute...
C Programming language problem I need to write a program which uses several threads (like 8...
C Programming language problem I need to write a program which uses several threads (like 8 threads for example) to sum up a number. The following program is using 1 thread but I need several threads to compile it. There was a hint saying that using multiple separate for loop and combining them will make a multi-threaded program. #include <stdio.h> #include <stdlib.h> #include <pthread.h> int sum; // this data is shared by the threads void *runner(void *param); // threads call...
Write a program to perform the following actions: the language is Java – Open an output...
Write a program to perform the following actions: the language is Java – Open an output file named “Assign14Numbers.txt” – Using a do-while loop, prompt the user for and input a count of the number of random integers to produce, make sure the value is between 35 and 150, inclusive. – After obtaining a good count, use a for-loop to generate the random integers in the range 0 ... 99, inclusive, and output each to the file as it is...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT