Advertisement
lameski

Untitled

Mar 30th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.13 KB | None | 0 0
  1.  
  2. import java.util.Random;
  3.  
  4. public class TenThreads {
  5. /* private static class WorkerThread extends Thread {
  6. int max = Integer.MIN_VALUE;
  7. int[] ourArray;
  8.  
  9. public WorkerThread(int[] ourArray) {
  10. this.ourArray = ourArray;
  11. }
  12.  
  13. // Find the maximum value in our particular piece of the array
  14. public void run() {
  15. for (int i = 0; i < ourArray.length; i++)
  16. max = Math.max(max, ourArray[i]);
  17. }
  18.  
  19. public int getMax() {
  20. return max;
  21. }
  22. }*/
  23. private static class WT implements Runnable{
  24. int max=Integer.MIN_VALUE;
  25. int [] niza;
  26. public WT(int [] niza){
  27. this.niza=niza;
  28. }
  29. public void run(){
  30. for (int i = 0; i < niza.length; i++)
  31. max = Math.max(max, niza[i]);
  32. }
  33. public int getMax() {
  34. return max;
  35. }
  36. }
  37.  
  38. public static void main(String[] args) {
  39. WT[] instanceWT = new WT[20];
  40. Thread[] threads= new Thread[20];
  41. int[][] bigMatrix = getBigHairyMatrix();
  42. int max = Integer.MIN_VALUE;
  43.  
  44. // Give each thread a slice of the matrix to work with
  45. for (int i = 0; i < 20; i++) {
  46. instanceWT[i] = new WT(bigMatrix[i]);
  47. threads[i]=new Thread(instanceWT[i]);
  48. threads[i].start();
  49. }
  50.  
  51. // Wait for each thread to finish
  52. try {
  53. for (int i = 0; i < 20; i++) {
  54. threads[i].join(); // why is this needed
  55. max = Math.max(max, instanceWT[i].getMax());
  56. }
  57. } catch (InterruptedException e) {
  58. // fall through
  59. }
  60.  
  61. System.out.println("Maximum value was " + max);
  62. }
  63.  
  64. static int[][] getBigHairyMatrix() {
  65. int x = 100;
  66. int y = 100;
  67.  
  68. int[][] matrix = new int[x][y];
  69. Random rnd = new Random();
  70.  
  71. for (int i = 0; i < x; i++)
  72. for (int j = 0; j < y; j++) {
  73. matrix[i][j] = rnd.nextInt(100);
  74. }
  75. matrix[5][7]=Integer.MAX_VALUE;
  76. return matrix;
  77. }
  78.  
  79. }
  80. // join() metodot e neophoden bidejki dokolku ne e implementiran vo zadacata na mestoto kade se pobaruva maksimumot od sekoj thread
  81. // mozebi toj thread ne e zavrshil so presmetkata i ke dade nekoj maksimum koj e momentalen i neznaci deka e tocniot maksimum.
  82. // join() ni ovozmozuva da ne se povika metodot getMax() pred threadot da zavrshi so svojata presmetka , odnosno dodeka da umre.
  83. //
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement