Question

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:

Homework Answers

Answer #1

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. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks


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
Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
I'm generating a random number every 10 second and Storing and Updating the number every 10...
I'm generating a random number every 10 second and Storing and Updating the number every 10 second when I generate new number in UpdateInt method. However, In my main method when I called UpdateInt method it generate every 10 second new number but it doesn't update and store in the arraylist. ***I want the Runnable to be in the arraylist method. Not in main method. my goal is to send the arraylist that has the update number*** import java.util.ArrayList; import...
The following program creates a linked list which contains 5 links. Add a method called doubleValue()...
The following program creates a linked list which contains 5 links. Add a method called doubleValue() to the LinkedList class. The doubleValue() method must double the value of the number data field in each link. Add the required code to the main() method to call the doubleValue() method and display the revised list. public class Link { private int number; private Link next;      public Link(int x) { number = x; }    public void displayLink() { System.out.println("The number is:...
The following program creates a linked list which contains 5 links. Add a method called doubleValue()...
The following program creates a linked list which contains 5 links. Add a method called doubleValue() to the LinkedList class. The doubleValue() method must double the value of the number data field in each link. Add the required code to the main() method to call the doubleValue() method and display the revised list. public class Link { private int number; private Link next;      public Link(int x) { number = x; }    public void displayLink() { System.out.println("The number is:...
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses...
Given main() complete the Stack class by writing the methods push() and pop(). The stack uses an array of size 5 to store elements. The command Push followed by a positive number pushes the number onto the stack. The command Pop pops the top element from the stack. Entering -1 exits the program. Ex. If the input is Push 1 Push 2 Push 3 Push 4 Push 5 Pop -1 the output is Stack contents (top to bottom): 1 Stack...
/* This program should check if the given integer number is prime. Reminder, an integer number...
/* This program should check if the given integer number is prime. Reminder, an integer number greater than 1 is prime if it divisible only by itself and by 1. In other words a prime number divided by any other natural number (besides 1 and itself) will have a non-zero remainder. Your task: Write a method called checkPrime(n) that will take an integer greater than 1 as an input, and return true if that integer is prime; otherwise, it should...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*;...
1) Consider the following Java program. Which statement updates the appearance of a button? import java.awt.event.*; import javax.swing.*; public class Clicker extends JFrame implements ActionListener {     int count;     JButton button;     Clicker() {         super("Click Me");         button = new JButton(String.valueOf(count));         add(button);         button.addActionListener(this);         setSize(200,100);         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         setVisible(true);     }     public void actionPerformed(ActionEvent e) {         count++;         button.setText(String.valueOf(count));     }     public static void main(String[] args) { new Clicker(); } } a. add(button);...
Write a Java program that asks the user to enter an array of integers in the...
Write a Java program that asks the user to enter an array of integers in the main method. The program should prompt the user for the number of elements in the array and then the elements of the array. The program should then call a method named isSorted that accepts an array of and returns true if the list is in sorted (increasing) order and false otherwise. For example, if arrays named arr1 and arr2 store [10, 20, 30, 41,...
Complete the // TODO sections in the EasyRental class. Create a method that implements an iterative...
Complete the // TODO sections in the EasyRental class. Create a method that implements an iterative sort that sorts the vehicle rentals by color in ascending order (smallest to largest) Create a method to binary search for a vehicle based on a color, that should return the index where the vehicle was found or -1 You are comparing Strings in an object not integers. Ex. If the input is: brown red white blue black -1 the output is: Enter the...
Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads...
Here's the requirement. Write a client program Subset.java that takes a command-line integer k , reads in a sequence of strings from standard input using StdIn.readString() , and prints out exactly k of them, uniformly at random. Each item from the sequence can be printed out at most once. You may assume that 0 k N , where N is the number of string on standard input. The running time of the program must be linear in the size of...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class...
1) Consider the following Java program, which one of the following best describes "setFlavor"? public class Food {     static int count;     private String flavor = "sweet";     Food() { count++; }     void setFlavor(String s) { flavor = s; }     String getFlavor() { return flavor; }     static public void main(String[] args) {         Food pepper = new Food();         System.out.println(pepper.getFlavor());     } } a. a class variable b. a constructor c. a local object variable d....