Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package hw11;
- import java.util.Scanner;
- class OwnSumThread extends Thread {
- private int sum, i, j;
- private int[] array;
- public OwnSumThread(int i, int j, int[] array) {
- sum = 0;
- this.i = i;
- this.j = j;
- this.array = array;
- }
- public int getSum() {
- return sum;
- }
- @Override
- public void run() {
- for (int l = i; l <= j; l++) {
- sum += array[l];
- }
- }
- }
- public class ConcurrencyTask1 {
- public static void setArray(int[] array) {
- System.out.println("Введите ваш массив:");
- Scanner sc = new Scanner(System.in);
- for (int i = 0; i < array.length; i++) {
- array[i] = sc.nextInt();
- }
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- System.out.println("Введите размерность массива:");
- int n = sc.nextInt();
- int[] array = new int[n];
- setArray(array);
- System.out.println("Введите количество потоков:");
- int k = sc.nextInt();
- int m = n / k;
- int l = 0;
- OwnSumThread[] threads = new OwnSumThread[k];
- for (int i = 0; i < k - 1; i++) {
- threads[i] = new OwnSumThread(l, m, array);
- threads[i].start();
- l = m + 1;
- m += m;
- if (i == k - 2) {
- threads[i + 1] = new OwnSumThread(l, array.length - 1, array);
- threads[i + 1].start();
- }
- }
- int result = 0;
- for (int i = 0; i < k; i++) {
- result += threads[i].getSum();
- }
- System.out.println(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment