Advertisement
salercode

Lab2OsZad2

Mar 10th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. import java.util.Random;
  2. import java.util.*;
  3. import java.io.*;
  4.  
  5. public class TenThreads {
  6.     private static class WorkerThread implements Runnable {
  7.         int max = Integer.MIN_VALUE;
  8.         int[] ourArray;
  9.  
  10.         public WorkerThread(int[] ourArray) {
  11.             this.ourArray = ourArray;
  12.         }
  13.  
  14.         // Find the maximum value in our particular piece of the array
  15.         public void run() {
  16.             for (int i = 0; i < ourArray.length; i++)
  17.                 max = Math.max(max, ourArray[i]);
  18.         }
  19.  
  20.         public int getMax() {
  21.             return max;
  22.         }
  23.     }
  24.  
  25.     public static void main(String[] args) {
  26.         WorkerThread[] threads = new WorkerThread[20];
  27.         Thread threads1[] =new Thread[20];
  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 < 20; i++) {
  33.             threads[i] = new WorkerThread(bigMatrix[i]);
  34.             threads1[i]=new Thread(threads[i]);
  35.             threads1[i].start();
  36.         }
  37.  
  38.         // Wait for each thread to finish
  39.         try {
  40.             for (int i = 0; i < 20; i++) {
  41.                 threads1[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. }
  67. //Dokolku e nemame komandata join bi go dobile tekovniot maksimum na nitkata bidekji ne sme cekale da zavrsi edna nitkata,nemozeme da predvidime koj e toj element bideki seuste ne e zavrsena,mozda izpustila nekoj pogolem element vo ostanatiot del od nizata
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement