Question: Explain in the following code, how we can avoid race conditions. class Counter { int count; public void increment ( ) { count + +

Explain in the following code, how we can avoid race conditions.
class Counter
{
int count;
public void increment()
{
count++; // count = count +1
}
}
public class SyncDemo
{
public static void main(String[] args)
{
Counter c = new Counter();
// c.increment();
// c.increment();
Thread t1= new Thread(new Runnable()
{
public void run()
{
for(int i=1;i<=20000;i++)
{
c.increment();
}
}
});
Thread t2= new Thread(new Runnable()
{
public void run()
{
for(int i=1;i<=20000;i++)
{
c.increment();
}
}
});
t1.start();
t2.start();
try {
t1.join();
} catch (InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
t2.join();
} catch (InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Count "+ c.count);
}
}
wait() operation
wait(S){
while (S <=0)
// busy wait
S--;
}
signal() operation
signal(S){
S++;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!