Reputation: 31
Consider the below code for Thread Synchronization Method and a Synchronization Block
public class ThreadSynchronizationPartI {
public static int myValue=1;
public static void main(String [] args)
{
Thread t=new Thread(()->
{
while(true)
{
updateBalance();
}
});
t.start();
t=new Thread(()->{
while(true)
{
monitorBalance();
}
});
t.start();
}
public static synchronized void updateBalance(){
System.out.println("start "+myValue);
myValue = myValue + 1;
// myValue = myValue - 1;
System.out.println("end "+myValue);
}
public static synchronized void monitorBalance(){
int b=myValue;
if(b>1)
{
System.out.println("B is greater than 1 by"+(b-1));
System.exit(1);
}
}
}
Why Does it give the following output: start 1 end 2 start 2 end 3 start 3 end 4 start 4 end 5 start 5 end 6 start 6 end 7 start 7 end 8 B is greater than 1 by 7
Can anyone explain?
Upvotes: 0
Views: 83
Reputation: 419
The execution of your program will start from main(). Initially the value of myValue is 1 and a new thread t will be created. Until the condition is true the while loop will be executed. When the control will reach updateBalance(), it will jump to that method and the println() will print the value of myValue which is 1. Hence the output will be : start 1
it will then increase the value of myValue to +1 and as a result the next println() would print the output as : end 2
. When the condition for next thread will be true in while loop, the control will be transferred there. The monitorBalance() will be called and b is initialized the value of myValue. When the condition b>1
evaluates to true it will print : B is greater than 1 by (b-1)
.
Upvotes: 1