codisinmyvines

forKsenia

Nov 23rd, 2021
1,136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.75 KB | None | 0 0
  1. package hw11;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class OwnSumThread extends Thread {
  6.     private int sum, i, j;
  7.     private int[] array;
  8.  
  9.     public OwnSumThread(int i, int j, int[] array) {
  10.         sum = 0;
  11.         this.i = i;
  12.         this.j = j;
  13.         this.array = array;
  14.     }
  15.  
  16.     public int getSum() {
  17.         return sum;
  18.     }
  19.  
  20.     @Override
  21.     public void run() {
  22.         for (int l = i; l <= j; l++) {
  23.             sum += array[l];
  24.         }
  25.     }
  26. }
  27.  
  28. public class ConcurrencyTask1 {
  29.     public static void setArray(int[] array) {
  30.         System.out.println("Введите ваш массив:");
  31.         Scanner sc = new Scanner(System.in);
  32.         for (int i = 0; i < array.length; i++) {
  33.             array[i] = sc.nextInt();
  34.         }
  35.     }
  36.  
  37.     public static void main(String[] args) {
  38.         Scanner sc = new Scanner(System.in);
  39.         System.out.println("Введите размерность массива:");
  40.         int n = sc.nextInt();
  41.         int[] array = new int[n];
  42.         setArray(array);
  43.         System.out.println("Введите количество потоков:");
  44.         int k = sc.nextInt();
  45.         int m = n / k;
  46.         int l = 0;
  47.         OwnSumThread[] threads = new OwnSumThread[k];
  48.         for (int i = 0; i < k - 1; i++) {
  49.             threads[i] = new OwnSumThread(l, m, array);
  50.             threads[i].start();
  51.             l = m + 1;
  52.             m += m;
  53.             if (i == k - 2) {
  54.                 threads[i + 1] = new OwnSumThread(l, array.length - 1, array);
  55.                 threads[i + 1].start();
  56.             }
  57.         }
  58.         int result = 0;
  59.         for (int i = 0; i < k; i++) {
  60.             result += threads[i].getSum();
  61.         }
  62.         System.out.println(result);
  63.     }
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment