1

I have to create exactly 2 classes: Main with main method, and other one, let's say Class1 that implements matrix multiplication. I want Class1 to read data from file, and perform matrix multiplication using threads.

I know I can create multiple instances and pass parameter to constructors, but what I need is to create one instance of Class1 and read file once, and run portion of calculation on multiple threads.

It's incorrect, but it should kind of have passing run method with parameter:

public class Main {
    public static void main(String[] args) {

        Class1 c = new Class1();

        ArrayList <Thread> a = new ArrayList<>();

        for (int i = 0; i < 4; i++) {
            a.add(i, new Thread(c));
        }

        for (int i = 0; i < 4; i++) {
            a.get(i).start(index1,index2);
        }
    }
}
Jiih
  • 11
  • 3

2 Answers2

0

To spawn a new thread in Java you need to call start() method though you override run() method.

By this I mean:

class ClassA implements Runnable {
...
}

//Creates new thread
(new ClassA()).start();

//Runs in the current thread:
(new ClassA()).run();

Calling run() will execute the code in the current thread.

Chris
  • 5,584
  • 9
  • 40
  • 58
0

You need to pass the parameter in the constructor to the thread object:

public class MyThread implements Runnable {

   public MyThread(Object parameter) {
       // store parameter for later user
   }

   public void run() {
   }
}

and invoke it thus:

Runnable r = new MyThread(param_value);
new Thread(r).start();

For your situation you should create a constructor such as

public MyThread(int x, int y){
// store parameter for later user
}

https://stackoverflow.com/a/877113/1002790

Community
  • 1
  • 1
Salih Erikci
  • 5,076
  • 12
  • 39
  • 69