1

I want to modify an array inside different threads, let me explain.

I have a 'parent' thread that contains an array of Objects, initially it's empty. What i want to implement with the multithread is a way of filling in this array. For example, thread one will make requests and fill positions 0-20, thread 2 21-40 and so on. In C this would be easy, i would just pass the pointer and work from there.

Since java does not allow it i don't know how to do it. I can't return anything from the run(), nor pass it as parameter in the thread constructor since the array wont be accessible from the thread above. I hope someone knows a clean way to do so.

myclass extends thread and overrides the run.

3
  • 2
    give your code and if have troubles,we will help you Commented Apr 12, 2013 at 17:04
  • For clarification, you mentioned a parent thread, so does that mean that you have one thread running which at some points spawns a new thread? Commented Apr 12, 2013 at 17:07
  • 2
    Do not understand what you mean that you could have passed the pointer in C, but you can't pass the reference because it's java? The fundamental structure shouldn't really be that different, the reference is java is just a pointer really. Commented Apr 12, 2013 at 17:12

2 Answers 2

2

There is no reason to extend Thread. A Thread is a resource for doing units of work, you're not creating a new type of resource, you're defining a unit of work. Just implement runnable, then you can define your own constructor and pass in the Array.

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));
Sign up to request clarification or add additional context in comments.

Comments

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

And so on. It's pretty much the same as C, except instead of passing a pointer to the starting array element, you instead pass the entire array along with the lower and upper array bounds that you want modified by that thread.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.