Java多线程 - 将参数传递给单个实例

时间:2013-06-09 13:31:57

标签: java multithreading

我必须创建两个类: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);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

要在Java中生成新线程,您需要通过覆盖start()方法调用run()方法。

我的意思是:

class ClassA implements Runnable {
...
}

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

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

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

答案 1 :(得分: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

相关问题