You are working as a software engineer and you developed a m
Solution
let you your global array of integers be integers[]
The statement
is actually a sequence of three operations:
Suppose that each of several threads performs these three steps. Remember that it\'s possible for two threads to run at the same time, and even if there is only one processor, it\'s possible for that processor to switch from one thread to another at any point. Suppose that while one thread is between Step 2 and Step 3, another thread starts executing the same sequence of steps. Since the first thread has not yet stored the new value in integer[1], the second thread reads the old value of integer[1] and adds one to that old value. Both threads have computed the same new value for integer[1], and both threads then go on to store that value back into integer[1] by executing Step 3. After both threads have done so, the value of count has gone up only by 1 instead of by 2! This type of problem is called a race condition.
This occurs when one thread is in the middle of a multi-step operation, and another thread can change some value or condition that the first thread is depending upon. (The first thread is \"in a race\" to complete all the steps before it is interrupted by another thread.)
To fix the problem of race conditions, there has to be some way for a thread to get exclusive access to a shared resource.It\'s done with synchronized methods and with the synchronized statement.
These are used to protect shared resources by making sure that only one thread at a time will try to access the resource.
mutual exclusion, which means that exclusive access to a resource is only guaranteed if every thread that needs access to that resource uses synchronization.
In our scenario:
Every thread must check if the array integers is accessed by any other thread it must wait untill the other thread releases it and only one thread must access the shared global array at a time.
