Advertisement
Guest User

Untitled

a guest
Mar 31st, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class TenThreads {
  4. private static class WorkerThread implements Runnable {
  5.  
  6. Thread t;
  7.  
  8. int max = Integer.MIN_VALUE;
  9. int[] ourArray;
  10.  
  11. public WorkerThread(int[] ourArray) {
  12. this.ourArray = ourArray;
  13. }
  14.  
  15. @Override// Find the maximum value in our particular piece of the array
  16. public void run() {
  17. for (int i = 0; i < ourArray.length; i++)
  18. max = Math.max(max, ourArray[i]);
  19. }
  20.  
  21. public int getMax() {
  22. return max;
  23. }
  24.  
  25. public void start()
  26. {
  27. t=new Thread(this);
  28. t.start();
  29. }
  30. }
  31.  
  32. public static void main(String[] args) {
  33. WorkerThread[] threads = new WorkerThread[20];
  34. int[][] bigMatrix = getBigHairyMatrix();
  35. int max = Integer.MIN_VALUE;
  36.  
  37. // Give each thread a slice of the matrix to work with
  38. for (int i = 0; i < 20; i++) {
  39. threads[i] = new WorkerThread(bigMatrix[i]);
  40. threads[i].start();
  41. }
  42.  
  43. // Wait for each thread to finish
  44. try {
  45. for (int i = 0; i < 20; i++) {
  46. new Thread(threads[i]).join();
  47. // threads[i].join(); // Ova se koristi za da chekaat drugite nitki da zavrshi ednata za da pochne
  48. // drugata po nea, bez nea nema redosled koja bi zavrshila prva, vtora, itn.
  49. max = Math.max(max, threads[i].getMax());
  50. }
  51. } catch (InterruptedException e) {
  52. // fall through
  53. }
  54.  
  55. System.out.println("Maximum value was " + max);
  56. }
  57.  
  58. static int[][] getBigHairyMatrix() {
  59. int x = 100;
  60. int y = 100;
  61.  
  62. int[][] matrix = new int[x][y];
  63. Random rnd = new Random();
  64.  
  65. for (int i = 0; i < x; i++)
  66. for (int j = 0; j < y; j++) {
  67. matrix[i][j] = rnd.nextInt();
  68. }
  69.  
  70. return matrix;
  71. }
  72.  
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement