-1
public class Main {

    public static int array[];

    public static int sums[];

    public static void main(String[] args) {
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);
        int numbersCount = scanner.nextInt();
        int threadsCount = scanner.nextInt();

        array = new int[numbersCount];
        sums = new int[threadsCount];

        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(100);
        }

        long startTime = System.currentTimeMillis();

        int realSum = 0;

        for (int i = 0; i < array.length; i++) {
            realSum += array[i];
        }

        long time = System.currentTimeMillis() - startTime;

        System.out.println("Сумма через цикл - " + realSum);
        System.out.println("Время выполнения через цикл - " + time);

        
        long startTime1 = System.currentTimeMillis();

        int numberOfElementsInOneThread = numbersCount/threadsCount;
        int startThread = 0;
        int endThread = numberOfElementsInOneThread - 1;
        int[] sums = new int[threadsCount];
        for (int i = 0; i < threadsCount; i++) {
            SumThread sumThread = new SumThread(startThread, endThread, array);
            sums[i] = sumThread.Sum();
            startThread += numberOfElementsInOneThread;
            endThread += numberOfElementsInOneThread;
        }

        int byThreadSum = 0;

        for (int i = 0; i < sums.length; i++) {
            byThreadSum += sums[i];

        }
        long time1 = System.currentTimeMillis() - startTime1;

        System.out.println("Сумма через потоки - " + byThreadSum);
        System.out.println("Время выполнения через потоки - " + time1);
    }
}

public class SumThread extends Thread {
    private int from;
    private int to;
    private int[] sum;


    public SumThread(int from, int to, int[] sum) {

        this.from = from;
        this.to = to;
        this.sum = sum;
    }

    public int Sum () {
        int sum = 0;
        for (int j = this.from; j <= this.to; j++) {
            sum += this.sum[j];
        }
        return sum;
    }
}
2
  • 2
    В чем собственно заключается проблема? 21 ноя 2021 в 2:01
  • Сумма элементов массива через цикл и через потоки разная.В чем может быть ошибка?И как правильно переопределить метод run класса Thread в классе SumThread? 23 ноя 2021 в 1:55

1 ответ 1

0
import java.util.Random;
import java.util.Scanner;

public class Main {

    public static int array[];

    public static int sums[];

    public static int sum;


    public static void main(String[] args) {
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);
        int numbersCount = scanner.nextInt();
        int threadsCount = scanner.nextInt();

        array = new int[numbersCount];
        sums = new int[threadsCount];

        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(100);
        }

        long startTime = System.currentTimeMillis();

        int realSum = 0;

        for (int i = 0; i < array.length; i++) {
            realSum += array[i];
        }

        long time = System.currentTimeMillis() - startTime;

        System.out.println("Сумма через цикл - " + realSum);
        System.out.println("Время выполнения через цикл - " + time);

        // TODO: реализовать работу с потоками
        long startTime1 = System.currentTimeMillis();

        int byThreadSum = 0;
        int numberOfElementsInOneThread = (int)Math.ceil((double)(numbersCount) / (double)(threadsCount));
        int[] sums = new int[threadsCount];
        for (int i = 0; i < sums.length; i++) {
            SumThread SumThread = new SumThread(i * numberOfElementsInOneThread, (i + 1) * numberOfElementsInOneThread -1);
            SumThread.start();
            try {
                SumThread.join();
            } catch (InterruptedException e) {
                throw new IllegalArgumentException();
            }
            sums[i] = sum;
            byThreadSum += sums[i];
        }

        long time1 = System.currentTimeMillis() - startTime1;

        System.out.println("Сумма через потоки - " + byThreadSum);
        System.out.println("Время выполнения через потоки - " + time1);
    }
}

public class SumThread extends Thread {
    private int from;
    private int to;


    public SumThread(int from, int to) {

        this.from = from;
        this.to = to;

    }
    @Override
    public void run () {
        Main.sum = 0;
        for (int i = this.from; i <= this.to; i++) {
            if(i < Main.array.length)
            Main.sum += Main.array[i];
        }
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.