Note that there are some explanatory texts on larger screens.

plurals
  1. POMultithreading--Why one thread is doing all of the work?
    primarykey
    data
    text
    <p>I am multiplying two matrices using two threads (however, the program is written to scale up as well, so I could possibly use three, four, etc threads instead). Each thread calculates/does the work for one row (or column) of the final matrix. If one thread is doing work on a row, the other one(s) should not work on that row. It/they should move on to the next available row. </p> <p>First of all, I am not certain if the way I implemented the problem is correct. If you can see a better way, please let me know.</p> <p>Secondly, the way I have done it, every time I test it (with different size matrices--even huge ones), only one thread does the work. That is, each time, the same thread is getting access to the synchronized block of the run() method. The other threads are entering the run() method, but why is only one thread always gaining the lock and doing all of the work?</p> <p>This is my run method:</p> <pre><code> public void run() { System.out.println(Thread.currentThread().getName()); while (i &lt; number of columns in final matrix) { synchronized (this) { if (i &lt; number of columns in final matrix) { for (int j = 0; j &lt; Main.B[0].length; j++) { for (int k = 0; k &lt; Main.A[0].length; k++) { Main.C[i][j] += Main.A[i][k] * Main.B[k][j]; } } i++; } } } } </code></pre> <p>This is the code in my driver class that creates the threads and starts the program:</p> <pre><code>MyRunnable r = new MyRunnable(); Thread thread1 = new Thread(r); Thread thread2 = new Thread(r); thread1.start(); thread2.start(); try { thread1.join(); thread2.join(); } catch (InterruptedException ie) { System.out.println("\nThe following error occurred: " + ie); } } </code></pre> <p>I guess my question is two-fold--is my approach correct for the problem at hand? If so, (and if not), why is one thread always grabbing the lock and doing all of the work? I have checked the program with up to 6 threads on 20x20 matrices and always only one thread is doing the work.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload