我必须创建两个类: 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);
}
}
}
发布于 2013-06-09 13:39:01
要在Java语言中产生一个新线程,您需要调用start()
方法,尽管您覆盖了run()
方法。
我的意思是:
class ClassA implements Runnable {
...
}
//Creates new thread
(new ClassA()).start();
//Runs in the current thread:
(new ClassA()).run();
调用run()
将执行当前线程中的代码。
发布于 2013-06-09 13:43:35
您需要将构造函数中的参数传递给线程对象:
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/questions/17010132
复制相似问题