1

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];
    }
}
1
  • 1
    It would be better to change your method to private void addToArray(int start, int end) Commented Oct 9, 2018 at 2:00

1 Answer 1

2

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

2 Comments

Clarification: the point would be to fill up half of the array with one thread and the other half with another thread to save time, the array contains integers in my example, but it could be String or anything else.
Rather than incrementing aNumber I think that doing myArray[i] = aNumber + i; would be cleaner

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.