Home > OS >  How do I make threads refer to one common array?
How do I make threads refer to one common array?

Time:04-21

Program creates several threads that must add their own number into one array. The problem is that each thread refers to its own array, not the common one. How do I make threads refer to one common array?

My code:

private int[] array = new int[5];
private int number;

public Example(int number) {
    this.number = number;
}

public void addInArr(int x) {
    for(int i=0; i<array.length; i  ) {
        if(array[i]==0) {
            array[i] = x;
        }
        break;
    }
}

public void showArr() {
    for(int i=0; i<array.length; i  ) {
        System.out.print(array[i]   " ");
    }
}

public static void main(String[] args) {
    for(int i=1; i<6; i  ) {
        Example obj = new Example(i);
        obj.addInArr(i);
        obj.showArr();
    }
}

The code outputs: 1 0 0 0 0 2 0 0 0 0 3 0 0 0 0 4 0 0 0 0 5 0 0 0 0

The code must output: 1 2 3 4 5

CodePudding user response:

Perhaps the simplest is to define the array as a static member of the class.

public class StaticExample {
  private static int[] array = new int[5];
  ...
  public int getLength() {
    return array.length;
  }
}

CodePudding user response:

Your main thread is working in the same array. Your problem has nothing about multithreading. Your addInArray() method logic is not correct. You have 5 spots in your array but you always adds the new value at position 0. So the others spots are 0 as the default value for int.

You likely need a new variable to store the current position of your array starting as 0.

private int position = 0;

public void addInArr(int x) {
   array[position] = x;
   position  ;
}

Attention: If you add more than five numbers it will generate an error because your array has only 5 slots.

  • Related