我必须精确地创建2个类:Main与main方法,另外一个,让我们说实现矩阵乘法的Class1。我希望Class1从文件中读取数据,并使用线程执行矩阵乘法。
我知道我可以创建多个实例并将参数传递给构造函数,但是我需要创建一个Class1实例并读取一次文件,然后在多个线程上运行部分计算。
这是不正确的,但它应该带有带有参数的run方法:
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);
}
}
}
最佳答案
要在Java中生成新线程,尽管您要覆盖start()
方法,但仍需要调用run()
方法。
我的意思是:
class ClassA implements Runnable {
...
}
//Creates new thread
(new ClassA()).start();
//Runs in the current thread:
(new ClassA()).run();
调用
run()
将在当前线程中执行代码。