CandiedOrange is correct in his comment to your question. In other words, and given the method you mentioned, you should not worry about threadA calling the method at the same moment threadB is since both calls are writing to index. Had it been something like:
void incrementIndex() {
index++;
System.out.println(index); // threadB might have written to index
// before this statement is executed in threadA
}
threaA calls the method, increments index in the first statement, then attempts to read the value of index in the second statement, by which time threadB might have already made the call to the method and incremented index before threadA reads it and prints it. This is where synchronized
is necessary to avoid such a situation.
Now, if you still want to test synchronization, and you have access to the method code (or maybe you can do a similar prototype), you may consider something like the following that illustrates how multithreading behaves with synchronized methods:
public void theMethod(long value, String caller) {
System.out.println("thread" + caller + " is calling...");
System.out.println("thread" + caller + " is going to sleep...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread" + caller + " woke up!");
}
This should output:
threadA is calling...
threadA is going to sleep...
threadA woke up!
threadB is calling...
threadB is going to sleep...
threadB woke up!
Without the synchronized
keyword, the output be:
threadA is calling...
threadA is going to sleep...
threadB is calling...
threadB is going to sleep...
threadA woke up!
threadB woke up!