Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help creating multithreaded program

Status
Not open for further replies.

invalid6363

Programmer
Mar 21, 2008
24
US
i'm trying to do one of the exercises from my OS book. the exercise is about creating a multithreaded solution that performs matrix multiplication.(A[i,j] x B[i,j]= C[i,j])
it says that for this exercise you need to calculate each element C[i,j] in a separate worker thread. This will involve creating MxN worker threads.(this is the part that i don't quite understand how to do.)
here is my code:
Java:
public class WorkerThread implements Runnable

{
	private int m;

	private int n;

	private int k = 2;

	private int [][] A;

	private int [][] B;

	private int [][] C;

	public WorkerThread(int m, int n, int[][] A, int[][]B, int [][]C) {

		this.m = m;
		this.n = n;

		this.A = A;
		this.B = B;
		this.C = C;

	}

	public void run() {

		/* calculate the matrix product in C[row][col] */
		for(int i = 0;i < m;i++){
			for(int j = 0;j < n;j++){
				for(int h = 0;h < k;h++){
					C[i][j] += A[i][h] * B[h][j];
				}				
			}
		}
		System.out.println("Matrix C: ");

		for(int i = 0;i < m;i++){
			for(int j = 0;j < n;j++){
				System.out.print(" " + C[i][j]);
			}
			System.out.println();
		}
	}
	public static void main(String [] args){
		int m = 3;
		int n = 3;
		int A [][] = {{1,4},{2,5},{3,6}};
		int B [][] = {{8,7,6},{5,4,3}};
		int C [][] = new int [m][n];		
		WorkerThread worker1 = new WorkerThread(m, n, A, B, C);
		Thread thread1 = new Thread(worker1);
		thread1.start();
	}
}

this code works but it only uses a single thread to multiply the matrices and from what i understand i need to use more than one thread.
Does anybody have any suggestions or can explain the "create MxN threads" part?
thanks.
 
You're rigth, you're creating just a thread.

I'd create another class that implements Runnable and have this code

Code:
               for(int h = 0;h < k;h++){
                    C[i][j] += A[i][h] * B[h][j];

in its run method, creating a new thread on each invocations inside the loop.

Cheers,
Dian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top