Ya10
@Ya10

Создать код для вычисления суммы элементов масива в двух отдельных потоках. Как разбить процес на два потока?

Вот задание:
1. Create a class MySumCount which extends the Thread class. Add to class MySumCount two integer fields startIndex and stopIndex with setters and getters. Add to class MySumCount new field as array of integer type and setter for it. Add to class MySumCount new field resultSum of long type and getter for it.
2. Override the run() method of Thread. Add code to calculate sum of array elements from startIndex to stopIndex and save result to resultSum field.
3. Create a class Main with a main() method. Add to method main() code that declares local variable myArray as array of integer type (of 1000 size), and create two instances of MySumCount. Add code to fill all elements of myArray with random integer values generated from 0 to 1000 range. Add code to calculates sum of myArray elements in two separate thread and then printresult to console.


вот минимум ,что Я набросал:
public class MySumCount extends Thread {
    public int startIndex;
    public int stopIndex;
    public long resultSum;
    public int[] array = {startIndex, stopIndex};

    public long getResultSum() {
        return resultSum;
    }
    public void setArray(int[] array) {
        this.array = array;
    }
    public int getStartIndex() {
        return startIndex;
    }
    public void setStartIndex(int startIndex) {
        this.startIndex = startIndex;
    }
    public int getStopIndex() {
        return stopIndex;
    }
    public void setStopIndex(int stopIndex) {
        this.stopIndex = stopIndex;
    }

    @Override
    public void run() {
        for (int i = 0; i < array.length; i++)
            resultSum += array[i];
        System.out.println(resultSum);
    }
}

public class Main {
    public static void main(String[] args) {
        int[] arr = new int[1000];
        
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) Math.round((Math.random() * 1000));
            System.out.print(arr[i] + " ");
        }


Сумма элементов масива, это через метод фор, Я его запихнул в ран, затем, заполнить масив, рандомными числами в диапазоне до 1000, это тоже не сложно, но вот эти взаимодействия с гетерами и сетерами, разбивка процесса на два потока, это Я не понимаю, подскажите как решать?
  • Вопрос задан
  • 84 просмотра
Пригласить эксперта
Ответы на вопрос 1
@Akela_wolf
Extreme Programmer
MySumCount должен суммировать не весь массив, а от startIndex до endIndex
MySumCount не должен выводить сумму, только записать её в поле resultSum

Таким образом main:
1. Создает массив и заполняет его числами (лучше предсказуемыми, чтобы легко было проверить что там насчиталось)
2. Создает 2 экземпляра MySumCount, вызывает у них методы setArray, setStartIndex, setEndIndex
3. Запускает оба потока (метод start)
4. Ждет пока оба отработают (метод join)
5. Вычитывает из обоих результат (getResultSum)
6. Складывает, получает итоговую сумму в массиве и выводит её

Вот простой пример с тредами:
class Playground {
    static class Task extends Thread {

        public long delay = 1000;
        public int num = 0;

        @Override
        public void run() {
            System.out.println("Started " + num);
            try {
                Thread.sleep(delay);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
            System.out.println("Finished " + num);
        }
    }

    public static void main(String[ ] args) throws InterruptedException {
        final Task t1 = new Task();
        t1.num = 1;
        t1.delay = 2000;
        final Task t2 = new Task();
        t2.num = 2;
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println("Completed");
    }
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы