Crazy

Threads - Задача 2

Mar 13th, 2018
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class TenThreads {
  4.     private static class WorkerThread implements Runnable {
  5.         int max = Integer.MIN_VALUE;
  6.         int[] ourArray;
  7.  
  8.         public WorkerThread(int[] ourArray) {
  9.             this.ourArray = ourArray;
  10.         }
  11.  
  12.         // Find the maximum value in our particular piece of the array
  13.         public void run() {
  14.             for (int i = 0; i < ourArray.length; i++)
  15.                 max = Math.max(max, ourArray[i]);
  16.         }
  17.  
  18.         public int getMax() {
  19.             return max;
  20.         }
  21.     }
  22.  
  23.     public static void main(String[] args) {
  24.         WorkerThread[] threads = new WorkerThread[20];
  25.         Thread demThreads[] = new Thread[20];
  26.  
  27.  
  28.         int[][] bigMatrix = getBigHairyMatrix();
  29.         int max = Integer.MIN_VALUE;
  30.  
  31.         // Give each thread a slice of the matrix to work with
  32.         for (int i = 0; i < 10; i++) {
  33.             threads[i] = new WorkerThread(bigMatrix[i]);
  34.             demThreads[i] = new Thread(threads[i]);
  35.             demThreads[i].start();
  36.         }
  37.  
  38.         // Wait for each thread to finish
  39.         try {
  40.             for (int i = 0; i < 10; i++) {
  41.                 demThreads[i].join(); // why is this needed
  42.                 max = Math.max(max, threads[i].getMax());
  43.             }
  44.         } catch (InterruptedException e) {
  45.             // fall through
  46.         }
  47.  
  48.         System.out.println("Maximum value was " + max);
  49.     }
  50.  
  51.     static int[][] getBigHairyMatrix() {
  52.         int x = 100;
  53.         int y = 100;
  54.  
  55.         int[][] matrix = new int[x][y];
  56.         Random rnd = new Random();
  57.  
  58.         for (int i = 0; i < x; i++)
  59.             for (int j = 0; j < y; j++) {
  60.                 matrix[i][j] = rnd.nextInt();
  61.             }
  62.  
  63.         return matrix;
  64.     }
  65.  
  66. }
Advertisement
Add Comment
Please, Sign In to add comment