1

我必须准确地创建 2 个类:带有 main 方法的 Main 类,以及另一个类,比如实现矩阵乘法的 Class1。我希望 Class1 从文件中读取数据,并使用线程执行矩阵乘法。

我知道我可以创建多个实例并将参数传递给构造函数,但我需要的是创建一个 Class1 实例并读取一次文件,并在多个线程上运行部分计算。

这是不正确的,但它应该有传递带有参数的运行方法:

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);
        }
    }
}
4

2 回答 2

0

您需要将构造函数中的参数传递给线程对象:

public class MyThread implements Runnable {

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

   public void run() {
   }
}

并因此调用它:

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

对于您的情况,您应该创建一个构造函数,例如

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

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

于 2013-06-09T13:43:34.973 回答
0

要在 Java 中生成一个新线程,您需要调用start()方法,尽管您覆盖了run()方法。

我的意思是:

class ClassA implements Runnable {
...
}

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

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

调用run()将执行当前线程中的代码。

于 2013-06-09T13:39:01.103 回答