2013-04-12 34 views
1

我想修改不同线程内的一个数组,让我解释一下。Java多线程 - 单个数组更新

我有一个'父'线程包含一个对象数组,最初它是空的。我想用多线程实现的是填充这个数组的一种方法。例如,线程1将发出请求并填充位置0-20,线程2 21-40等等。在C中,这很容易,我只需传递指针并从那里开始工作。因为java不允许它,我不知道该怎么做。我不能从run()中返回任何东西,也不能将它作为线程构造函数的参数传递,因为数组不会从上面的线程访问。我希望有人知道一个干净的方式来做到这一点。

myclass扩展了线程并覆盖了运行。

+2

给你的代码,如果遇到问题,我们会帮你 – BlackJoker

+0

为了澄清,你提到父线程,这是否意味着你有一个线程在运行,其在某些点上产生一个新的线程? –

+2

不明白你的意思,你可能已经通过C中的指针,但你不能传递参考,因为它是Java?基本的结构不应该真的如此不同,参考是java * is *真的只是一个指针。 – Affe

回答

2

没有理由扩展线程。线程是用于完成工作单元的资源,不是创建新类型的资源,而是定义工作单元。只要实现runnable,那么你可以定义你自己的构造函数并传入数组。

public class ArrayPopulator implements Runnable { 

    private Object[] array; 
    private int minIndex; 
    private int maxIndex; 

    public ArrayPopulator(Object[] array, int minIndex, int maxIndex) { 
    //assignments 
    } 

    public void run() { 
    for (int i = minIndex; i <= maxIndex; i++) { 
     //you get the idea 
    } 
    } 
} 


Thread thread1 = new Thread(new ArrayPopulator(array, 0, 19)); 
Thread thread1 = new Thread(new ArrayPopulator(array, 20, 39)); 
+0

+1。优秀的答案! –

1
public void fillPositions(int[] array, int lowerBound, int upperBound) { 
    for(int i = lowerBound; i < upperBound; i++) { ... } 
} 

fillPositions(array, 0, 20); 
fillPositions(array, 20, 40); 

依此类推。它与C几乎相同,除了不是将指针传递给起始数组元素,而是将整个数组与您希望由该线程修改的较低和较高数组边界一起传递。