Question

In: Computer Science

Complete the following program. This program should do the following: 1. Creates a random integer in...

Complete the following program. This program should do the following:

1. Creates a random integer in the range 10 to 15 for variable: allThreads, to create a number of threads.

2. Creates a random integer for the size of an ArrayList: size.

3. Each thread obtains a smallest number of a segment of the array. To give qual sized segment to each thread we make the size of the array divisible by the number of threads: while(size%allThreads != 0)size++

4. The program gives random integers to the ArrayList: a.

5. To make sure the smallest number of the entire array is the same of your output, I made a method named: sequentialSmallest(a)

6. The program creates a number of threads. Each thread obtains the smallest number of a segment.

7. You need to complete the method: run() below.

Note: If your answer depends to a variable location that two or more threads are writing to it (changing its value), you must synchronize the variable.

import java.util.*;

public class Main {

public static void main(String[] args) {

  // This method is complete. Do not change it.

  new Main();

  }

  public Main() {

      Q1Threads();

}

private void Q1Threads(){

  // This method is complete. Do not change it.

    Random rand = new Random();

    int allThreads = rand.nextInt(5) + 10;

    int size = rand.nextInt(50) + 1;

    while(size%allThreads != 0)size++;

    ArrayList<Integer> a = new ArrayList<Integer>(size);

    for(int i = 0; i < size; i++)

      a.add(rand.nextInt(100) + 10);

    sequentialSmallest(a);

    MyThread[] thrds = new MyThread[allThreads];

    int segment = size/allThreads;

    for(int i = 0; i <allThreads ; i++) {

      int firstIndex = i * segment;

      int lastIndex = i * segment + segment -1;

      thrds[i] = new MyThread(a, firstIndex, lastIndex);

    }

   

    for(int i = 0; i < allThreads; i++)

      thrds[i].start();

   

    try{

      for(int i = 0; i < allThreads; i++)

        thrds[i].join();

    }catch(Exception e){

      System.out.println("Error: " + e);

      System.exit(0);

    }

    System.out.println("The smallest number is: " + Shared.result);

}

private static void sequentialSmallest(ArrayList<Integer> a) {

    // This method is complete. Do not change it.

    int smallest = a.get(0);

    for(int i = 0; i < a.size(); i++)

      if(a.get(i) < smallest)

        smallest = a.get(i);

   System.out.println("The list of random numbers is:");

    for(int i = 0; i < a.size(); i++)

      System.out.print(a.get(i) + ", ");

    System.out.println("\nThe smallest number from the sequential list is: " + smallest);

}

}

class MyThread extends Thread{

private ArrayList<Integer> a;

private int from, too;

public MyThread(ArrayList<Integer> a, int from, int too) {

    this.a = a;

    this.from = from;

    this.too = too;

}

public void run(){

    // Complete this method

}

}

Answer:

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. Also, please rate the answer.

CODE:

import java.util.*;

public class Main {
        public static void main(String[] args) {
                // This method is complete. Do not change it.
                new Main();
        }

        public Main() {
                Q1Threads();
        }

        private void Q1Threads() {
                // This method is complete. Do not change it.
                Random rand = new Random();
                int allThreads = rand.nextInt(5) + 10;
                int size = rand.nextInt(50) + 1;
                while (size % allThreads != 0)
                        size++;
                ArrayList<Integer> a = new ArrayList<Integer>(size);
                for (int i = 0; i < size; i++)
                        a.add(rand.nextInt(100) + 10);
                sequentialSmallest(a);
                MyThread[] thrds = new MyThread[allThreads];
                int segment = size / allThreads;
                for (int i = 0; i < allThreads; i++) {
                        int firstIndex = i * segment;
                        int lastIndex = i * segment + segment - 1;
                        thrds[i] = new MyThread(a, firstIndex, lastIndex);
                }
                for (int i = 0; i < allThreads; i++)
                        thrds[i].start();
                try {
                        for (int i = 0; i < allThreads; i++)
                                thrds[i].join();
                } catch (Exception e) {
                        System.out.println("Error: " + e);
                        System.exit(0);
                }
                System.out.println("The smallest number is: " + Shared.result);
        }

        private static void sequentialSmallest(ArrayList<Integer> a) {
                // This method is complete. Do not change it.
                int smallest = a.get(0);
                for (int i = 0; i < a.size(); i++)
                        if (a.get(i) < smallest)
                                smallest = a.get(i);
                System.out.println("The list of random numbers is:");
                for (int i = 0; i < a.size(); i++)
                        System.out.print(a.get(i) + ", ");
                System.out
                                .println("\nThe smallest number from the sequential list is: "
                                                + smallest);
        }
}

class MyThread extends Thread {
        private ArrayList<Integer> a;
        private int from, too;

        public MyThread(ArrayList<Integer> a, int from, int too) {
                this.a = a;
                this.from = from;
                this.too = too;
        }

        public void run() {
                // assuming from<=too and both are valid indices on a
                // taking element at from index as smallest
                int smallest = a.get(from);
                // looping through indices from+1 to too
                for (int i = from + 1; i <= too; i++) {
                        // if element at index i is smaller than smallest, updating smallest
                        if (a.get(i) < smallest) {
                                smallest = a.get(i);
                        }
                }
                // now we need to update Shared.result if necessary. since this is a
                // shared variable, we need to synchronize the access so that no two
                // objects can modify its value at the same time.
                synchronized (Shared.result) {
                        // if smallest is less than current Shared.result, updating
                        // Shared.result
                        if (smallest < Shared.result) {
                                Shared.result = smallest;
                        }
                }

        }
}

// a simple class to store the result
class Shared {
        // initializing result to max value an int can hold, so that all other
        // integers will be smaller than this value.
        static Integer result = Integer.MAX_VALUE;
}

/*OUTPUT (random)*/

The list of random numbers is:
57, 87, 26, 96, 39, 83, 75, 80, 44, 68, 107, 89, 15, 108, 109, 15, 74, 55, 83, 11, 79, 106, 61, 43, 
The smallest number from the sequential list is: 11
The smallest number is: 11

Related Solutions

Need a program in java that creates a random addition math quiz The program should ask...
Need a program in java that creates a random addition math quiz The program should ask the user to enter the following The smallest and largest positive numbers to be used when generating the questions - The total number of questions to be generated per quiz - The total number of the quiz's to create from then the program should generate a random math (Just addition) quiz from what the user entered
Write a program to produce an array of integer random numbers. Your program should find out...
Write a program to produce an array of integer random numbers. Your program should find out from the user how many numbers to store. It should then generate and store that many random integers (the random numbers must be between 1 and 999 inclusive). The program should then determine the smallest number, the largest number, and the average of all the numbers stored in the array. Finally, it should print out all the numbers on the screen, five numbers to...
java program Create a program that creates and prints a random phone number using the following...
java program Create a program that creates and prints a random phone number using the following format: XXX-XXX-XXXX. Make sure your output include the dashes.  Do not let the first three digits contain an 8 or 9 (HINT: do not be more restrictive than that) and make sure that the second set of three digits is not greater than 773. Helpful Hint:   Think though the easiest way to construct the phone number. Each digit does do not have to be determined...
Write a program that repeatedly generates a random integer in the range [1, 100], one integer...
Write a program that repeatedly generates a random integer in the range [1, 100], one integer at a time, and displays the generated numbers on the screen according to the following rules: If the second number generated is greater than the first number, they are displayed on the screen in the order of their input and while the next random number generated is greater than the previous one, the random number is displayed on the screen and the program continues....
Write a program that repeatedly generates a random integer in the range [1, 100], one integer...
Write a program that repeatedly generates a random integer in the range [1, 100], one integer at a time, and displays the generated numbers on the screen according to the following rules: If the second number generated is greater than the first number, they are displayed on the screen in the order of their input and while the next random number generated is greater than the previous one, the random number is displayed on the screen and the program continues....
Write a program that repeatedly generates a random integer in the range [1, 100], one integer...
Write a program that repeatedly generates a random integer in the range [1, 100], one integer at a time, and displays the generated numbers on the screen according to the following rules: If the second number generated is greater than the first number, they are displayed on the screen in the order of their input and while the next random number generated is greater than the previous one, the random number is displayed on the screen and the program continues....
write a program that creates steps. You are expected to take in a single positive integer...
write a program that creates steps. You are expected to take in a single positive integer which will be used as the number of steps in your stair case. The program only accepts integers greater than 0 and less than 500. If 0 is entered a message stating "Your staircase has no steps." and if the user enters a value greater than or equal to 500, a message stating "I can't build a staircase that tall." For all other values...
Write a complete program in java that will do the following:
Write a complete program in java that will do the following:Sports:             Baseball, Basketball, Football, Hockey, Volleyball, WaterpoloPlayers:           9, 5, 11, 6, 6, 7Store the data in appropriate arraysProvide an output of sports and player numbers. See below:Baseball          9 players.Basketball       5 players.Football           11 players.Hockey            6 players.Volleyball        6 players.Waterpolo       7 players.Use Scanner to provide the number of friends you have for a team sport.Provide an output of suggested sports for your group of friends. If your...
Write a Java program that creates an array with 20 random numbers between 1 and 100,...
Write a Java program that creates an array with 20 random numbers between 1 and 100, and passes the array to functions in order to print the array, print the array in reverse order, find the maximum element of the array, and find the minimum element of the array. The prototype of the methods: public static void printArray(int arr[]) public static void printArrayReverse(int arr[]) public static int searchMax(int arr[]) public static int searchMin(int arr[]) Sample output: Random Array: [17 67...
DO THIS PROGRAM IN JAVA Write a complete Java console based program following these steps: 1....
DO THIS PROGRAM IN JAVA Write a complete Java console based program following these steps: 1. Write an abstract Java class called Shape which has only one abstract method named getArea(); 2. Write a Java class called Rectangle which extends Shape and has two data membersnamed width and height.The Rectangle should have all get/set methods, the toString method, and implement the abstract method getArea()it gets from class Shape. 3. Write the driver code tat tests the classes and methods you...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT