Given the following Java code, which of the statement(s) are true considering cl
ID: 3573682 • Letter: G
Question
Given the following Java code, which of the statement(s) are true considering class Account?
class Account
{
private int balance = 10000;
public void debit(int amt)
{
if (amt < 0)
return;
synchronized(this)
{
balance -= amt;
}
}
}
1)Two concurrent threads cannot access balance
all answer are wrong
Two concurrent threads cannot access amt
Two concurrent threads cannot access either balance or amt
1)Two concurrent threads cannot access balance
2)all answer are wrong
3)Two concurrent threads cannot access amt
4)Two concurrent threads cannot access either balance or amt
Explanation / Answer
Ans) 1
Reason:
by using the synchronized(this) we are acquiring lock on the current class object.
Let suppose Threse are two threads Thread1 and Thread2 trying to access the debit() method ,the thread(say Thread1 ) which acquired lock on the current class object only can access the balance variable and perform operations.Then the other thread ( Thread2) will have to wait until the Thread1 completes its operation.Once the lock is released on the current class object then the other Thread(Thread2) will acquired lock on the current class object and can access the variable balance.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.