Friday, June 10, 2011

Multiply two arrays using two threads

import java.util.Random;

public class Matrix implements Runnable {

 static int matrixSize = 5000;

 static long mult = 0;
 static int m1[];
 static int m2[];

 static void init() {

  m1 = new int[matrixSize];
  m2 = new int[matrixSize];

  Random randomGenerator = new Random();

  for (int i = 0; i < matrixSize; i++) {
   
   m1[i] = randomGenerator.nextInt(10);
   m2[i] = randomGenerator.nextInt(10);

  }

 }

 public static void main(String[] args) {
               
  init();
                // create two threads
  Thread th1 = new Thread(new Matrix()); 
  Thread th2 = new Thread(new Matrix());

                // sets names
  th1.setName("1");
  th2.setName("2");

                // start threads
  th1.start();
  th2.start();

  try {
                        // joins threads to main thread
   th1.join();
   th2.join();
  } catch (InterruptedException e) {
   e.printStackTrace();
  }

  System.out.println("mult" + mult);
 }

 public void run() {

  if (Thread.currentThread().getName().equals("1")) {
   long localMult = 0;
   for (int i = 0; i < matrixSize / 2; i++) {
    localMult += m1[i] * m2[i];
   }
   sum(localMult);

  } else if (Thread.currentThread().getName().equals("2")) {
   long localMult = 0;
   for (int i = matrixSize / 2; i < matrixSize; i++) {
    localMult += m1[i] * m2[i];
   }
   sum(localMult);
  }
 }

 synchronized void sum(long amount) {
// this method is synchronized because this updates global variable
  System.out.println("Sum " + amount);
  mult += amount;
 }
}

No comments:

Post a Comment