Gergely Bertalan
Gergely Bertalan

Reputation: 53

How to store elements in ONE array using TWO threads in Java?

In my example I want to fill up myArray from indices 0 to 19 with integers from 100 to 119.

I want to use two threads running at the same time, one thread places values in the array from index 0 to index 9, the other thread from index 10 to index 19.

When I print out the elements of myArray, I expect to see this:

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119

But because the threads are running at the same time, both can access my values, and I get the wrong result, this:

100 101 102 103 104 105 106 107 108 109 100 101 102 103 104 105 106 107 108 109

I think the problem is at my addToArray() method where the threads access my aNumber variable.

Is this when we need synchronized? If yes, how?

Please see my code:

Main class:

public class ThreadMain {
    SimpleThread first;
    SimpleThread second;

    public ThreadMain(String firstName, String secondName) {
        first = new SimpleThread(firstName);
        second = new SimpleThread(secondName);
    }

    public static void main(String[] args) {
        ThreadMain threadMain = new ThreadMain("FirstThread", "SecondThread");
        threadMain.startThreads();
        threadMain.waitForThreadsToFinish();
        threadMain.displayArrayElements();

    }

    private void startThreads() {
        first.start();
        second.start();
    }

    /**
     * main thread sleeps while the other threads are working.
     */
    private void waitForThreadsToFinish() {
        while (first.isAlive() || second.isAlive()) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void displayArrayElements() {
        for (int i = 0; i < 20; ++i) {
            int element = SimpleThread.getArrayElement(i);
            System.out.println(element);
        }
    }
}

Thread class:

class SimpleThread extends Thread {

    private int startIndex;
    private int endIndex;
    private static int[] myArray = new int[20];
    private int aNumber = 100;

    public SimpleThread(String str) {
        super(str);
    }

    public void run() {

        if (getName().equals("FirstThread")) {
            startIndex = 0;
            endIndex = 10;
            addToArray();//store value of aNumber in myArray from index 0 to index 9.
        }
        if (getName().equals("SecondThread")) {
            startIndex = 10;
            endIndex = 20;
            addToArray();//store value of aNumber in myArray from index 10 to index 19.
        }
    }

    private void addToArray() {
        for (int i = startIndex; i < endIndex; ++i) {
            myArray[i] = aNumber;
            ++aNumber;
        }
    }

    public static int getArrayElement(int index) {
        return myArray[index];
    }
}

Upvotes: 1

Views: 2310

Answers (1)

dave
dave

Reputation: 11975

Your problem appears to be that both instances of SimpleThread assign values beginning with a starting value of 100 and go from there.

One way to achieve your desired result, would be to use something like:

private void addToArray(int startIndex, int endIndex) {
    for (int i = startIndex; i < endIndex; ++i) {
        myArray[i] = aNumber + startIndex; // Change is here
        ++aNumber;
    }
}

Upvotes: 2

Related Questions