Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this template, choose Tools | Templates
- * and open the template in the editor.
- */
- package multithreadeddotproduct;
- import java.util.Random;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- /**
- *
- * @author mvat
- */
- public class MultiThreadedDotProduct {
- private int[] vec1 = new int[1000];
- private int[] vec2 = new int[1000];
- private Integer result = 0;
- public MultiThreadedDotProduct() {
- Random rand = new Random();
- for(int i=0;i<1000;i++) {
- vec1[i] = rand.nextInt(100);
- vec2[i] = rand.nextInt(100);
- }
- PartialDotProduct p1 = new PartialDotProduct(0,50);
- PartialDotProduct p2 = new PartialDotProduct(51,99);
- ExecutorService taskList = Executors.newFixedThreadPool(2);;
- taskList.execute(p1);
- taskList.execute(p2);
- while(p1.getStatus() == false || p2.getStatus() == false) {
- try {
- Thread.sleep(1);
- } catch (InterruptedException ex) {
- Logger.getLogger(MultiThreadedDotProduct.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- System.out.println("final result = " + result);
- }
- private void incrementResult(int n) {
- result += n;
- System.out.println("result = " + result);
- }
- private class PartialDotProduct implements Runnable {
- private int minIndex;
- private int maxIndex;
- private volatile boolean status = false;
- public PartialDotProduct(int minIndex, int maxIndex) {
- this.minIndex = minIndex;
- this.maxIndex = maxIndex;
- }
- public boolean getStatus() {
- return status;
- }
- public void run() {
- int productSum = 0;
- for(int i = minIndex; i<= maxIndex; i++) {
- productSum += (vec1[i]*vec2[i]);
- try {
- Thread.sleep(5);
- } catch(InterruptedException ie) {}
- }
- System.out.println(productSum);
- incrementResult(productSum);
- status = true;
- }
- }
- }
Add Comment
Please, Sign In to add comment