Tuesday, October 2, 2012

multiply two matrices using two threads in java

Here i will show how to multiply two matrices using two threads. The work is fairly divided among the two threads with the help of a for loop and conditional operator.

public class MMM {

 
 public static void main(String args[]) {

  int matrixOne[][] = { { 5, 6, 7, 33 }, { 5, 6, 7, 32 },
    { 5, 6, 7, 321 }, { 8, 9, 10, 3 }, { 88, 77, 66, -9 } };

  int matrixTwo[][] = { { 1, 4, 7, 66 }, { 2, 5, 8, 54 },
    { 3, 6, 9, 55 }, { 3, 6, 9, 55 } };

  Matrix result = calculate(matrixOne,matrixTwo);
  
  printMatrix(result);

 }
 
 public static void printMatrix(Matrix result){
 
  for (int i = 0; i < result.matrixValues.length; i++) {
   System.out.println(" ");
   for (int outer = 0; outer < result.matrixValues[0].length; outer++) {
    System.out.print(" " + result.matrixValues[i][outer]);
   }
  }
  
  
 }
 
 public static Matrix calculate(int matrixOne[][],int matrixTwo[][]){

  Matrix m1 = new Matrix(matrixOne);
  Matrix m2 = new Matrix(matrixTwo);
   
  Matrix m3 = MatrixCreator.getMatrix(m1, m2);
  
  Matrixthread mt[] = new Matrixthread[2];

  for (int i = 0; i < 2; i++) {
   mt[i] = new Matrixthread(m1,m2,m3);
   mt[i].setName(Integer.toString(i));
  }

  for (int i = 0; i < mt.length; i++) {
   mt[i].start();
  }

  for (int i = 0; i < mt.length; i++) {
   try {
    mt[i].join();
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }

  return m3;
 }
}

class Matrix {

 int matrixValues[][];

 Matrix(int matrixValues[][]) {
  this.matrixValues = matrixValues;
 }
}

class MatrixCreator {

 public static Matrix getMatrix(Matrix m1, Matrix m2) {

  int matrixThree[][] = new int[m1.matrixValues.length][m2.matrixValues[1].length];

  for (int i = 0; i < m1.matrixValues.length; i++) {

   for (int j = 0; j < m2.matrixValues[0].length; j++) {
    matrixThree[i][j] = 0;
   }
  }

  Matrix m3 = new Matrix(matrixThree);
  return m3;

 }
}

class Matrixthread extends Thread {

 int row = 0;

 int matrixOne[][];
 int matrixTwo[][];
 int matrixThree[][];

 Matrixthread(Matrix m1, Matrix m2,Matrix m3) {

  this.matrixOne = m1.matrixValues;
  this.matrixTwo = m2.matrixValues;
  this.matrixThree = m3.matrixValues;

 }

 public void run() {

  for (int matrixOneRow = (Thread.currentThread().getName().equals("1") ? 0
    : 1); matrixOneRow < this.matrixOne.length; matrixOneRow += 2) {

   for (int matrixTwoCol = 0; matrixTwoCol < this.matrixTwo[0].length; matrixTwoCol++) {

    for (int columns = 0; columns < this.matrixTwo.length; columns++) {

     this.matrixThree[matrixOneRow][matrixTwoCol] = this.matrixThree[matrixOneRow][matrixTwoCol]
       + this.matrixOne[matrixOneRow][columns]
       * this.matrixTwo[columns][matrixTwoCol];

    }

   }

  }

 }

}

Monday, October 1, 2012

Alternating execution of threads in java

Have you ever come across a need to execute two threads alternately? well to be truthful i never had the need, but this idea just came up and i decided to actually write the code that could make this happen. In the code below i intentionally inserted a this.sleep(1000); to clearly show that the threads do in fact execute the way intended.
public class AltThread {

 public static void main(String[] args) {

  Q ob = new Q();

  new thread1(ob);
  new thread2(ob); 
  
 }
}

class thread1 extends Thread {

 Q ob;
 
 thread1(Q ob) {
  this.ob = ob;
  this.start();
 }

 public void run() {
  while (true) {
   ob.one();
  }
 }
}

class thread2 extends Thread {

 Q ob;
 
 thread2(Q ob) {
  this.ob = ob;
  this.start();
 }

 public void run() {
  while (true) {
   ob.two();
   try {
    this.sleep(1000);
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
}


class Q{
 
 static  boolean toggle = false; 
 
 public synchronized void one(){
  while(!toggle){
   try {
    wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  toggle = false;
  notify();
  System.out.println("One"); 
 }
 
 public synchronized void two(){
  while(toggle){
   try {
    wait();
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  toggle = true;
  notify();
  
  System.out.println("Two");
 } 
}

Wednesday, September 26, 2012

addition of array using _beginthread

This example unlike the previous one, sleeps for a sufficient time until both threads complete their part of the addition.

#include "StdAfx.h"
#include 
#include 
#include 
#include      // needed for _beginthread()

void  partSum( void * );   // function prototype

using namespace std;

#define N 100  

int arraySum[N];

int main()
{
    // Our program's first thread starts in the main() function.

    printf( "Now in the main() function.\n" );

    for(int i = 0 ; i  < 100 ; i++){
        arraySum[i] = i;
    }

    // Let's now create our second thread and ask it to start
    // in the silly() function.
 int result_1 = 1;
    int result_2 = 2;


    _beginthread( partSum, 0, (void*)&result_1 );
    _beginthread( partSum, 0, (void*)&result_2 );

    Sleep( 1000 );

 int fullSum =  result_1 + result_2;
 cout << " fullSum" << fullSum << endl;

    int a;
    cin >> a;

}

void  partSum( void *arg )
{

 int *arg2 = (int*) arg;
    int partialSum = 0;
    for(int i =(N/2) * (*arg2 - 1); i < (N/2) * *arg2 ; i++){
    partialSum += arraySum[i];
    }

    cout << "partialSum" << *arg2 << "= " <<   partialSum << endl;  
 *arg2 = partialSum;
}

addition of array using _beginthreadex WaitForSingleObject

The following code adds all the elements in the array "arraySum" using two threads. This code uses two threads to perform the addition operation and also it uses thread wait call to wait for each of the two threads to exit before they are added by the main thread.

#include "StdAfx.h"
#include <iostream>
#include <windows.h>
#include <process.h>

using namespace std;

#define N 100

int arraySum[N];

unsigned int __stdcall  partSum( void * );   // function prototype

int main()
{

  for(int i = 0 ; i  < N ; i++){
        arraySum[i] = i;
     }

     int  uiThread1ID = 1;
  int  uiThread1ID2 = 2;

     HANDLE  th =  (HANDLE)_beginthreadex(NULL, 0, partSum,(void*)&uiThread1ID, NULL, 0);
  WaitForSingleObject(th, INFINITE/*optional timeout, in ms*/);

  HANDLE  th2 =  (HANDLE)_beginthreadex(NULL, 0, partSum,(void*)&uiThread1ID2, NULL, 0);
  WaitForSingleObject(th2, INFINITE/*optional timeout, in ms*/);

  int fullSum =  uiThread1ID + uiThread1ID2;

  cout << " fullSum" << fullSum << endl;

     int a;
     cin >> a;

    return 0;
}


unsigned int __stdcall  partSum( void *arg )
{
 int *arg2 = (int*) arg;
    int partialSum = 0;
 
    for(int i =(N/2) * (*arg2 - 1); i < (N/2) * *arg2 ; i++){
    partialSum += arraySum[i];
    } 

 cout << "partialSum" << *arg2 << "= " <<   partialSum << endl;
 *arg2 = partialSum;

 return 0;
}