Guest User

Untitled

a guest
Sep 24th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.32 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5.  
  6. package multithreadeddotproduct;
  7.  
  8. import java.util.Random;
  9. import java.util.concurrent.ExecutorService;
  10. import java.util.concurrent.Executors;
  11. import java.util.concurrent.TimeUnit;
  12. import java.util.logging.Level;
  13. import java.util.logging.Logger;
  14. /**
  15.  *
  16.  * @author mvat
  17.  */
  18. public class MultiThreadedDotProduct {
  19.     private int[] vec1 = new int[1000];
  20.     private int[] vec2 = new int[1000];
  21.     private Integer result = 0;
  22.  
  23.     public MultiThreadedDotProduct() {
  24.         Random rand = new Random();
  25.  
  26.         for(int i=0;i<1000;i++) {
  27.             vec1[i] = rand.nextInt(100);
  28.             vec2[i] = rand.nextInt(100);
  29.         }
  30.  
  31.  
  32.         PartialDotProduct p1 = new PartialDotProduct(0,50);
  33.         PartialDotProduct p2 = new PartialDotProduct(51,99);
  34.  
  35.         ExecutorService taskList = Executors.newFixedThreadPool(2);;
  36.         taskList.execute(p1);
  37.         taskList.execute(p2);
  38.        
  39.         while(p1.getStatus() == false || p2.getStatus() == false) {
  40.             try {
  41.                 Thread.sleep(1);
  42.             } catch (InterruptedException ex) {
  43.                 Logger.getLogger(MultiThreadedDotProduct.class.getName()).log(Level.SEVERE, null, ex);
  44.             }
  45.         }
  46.  
  47.         System.out.println("final result = " + result);
  48.        
  49.     }
  50.  
  51.     private void incrementResult(int n) {
  52.         result += n;
  53.         System.out.println("result = " + result);
  54.     }
  55.  
  56.     private class PartialDotProduct implements Runnable {
  57.         private int minIndex;
  58.         private int maxIndex;
  59.         private volatile boolean status = false;
  60.  
  61.         public PartialDotProduct(int minIndex, int maxIndex) {
  62.             this.minIndex = minIndex;
  63.             this.maxIndex = maxIndex;
  64.         }
  65.  
  66.         public boolean getStatus() {
  67.             return status;
  68.         }
  69.  
  70.         public void run() {
  71.             int productSum = 0;
  72.             for(int i = minIndex; i<= maxIndex; i++) {
  73.                 productSum += (vec1[i]*vec2[i]);
  74.                 try {
  75.                     Thread.sleep(5);
  76.                 } catch(InterruptedException ie) {}
  77.             }
  78.  
  79.            System.out.println(productSum);
  80.            incrementResult(productSum);
  81.            status = true;
  82.         }
  83.  
  84.     }
  85. }
Add Comment
Please, Sign In to add comment