What is Synchronized method?

Example:
class Account {
private int balance = 50;
public int getBalance() {
return balance;
}
public void withdraw(int amount) {
balance = balance - amount;
}}
class demo implements Runnable
{
private Account acc=new Account();
public void run(){
for(int i=0;i<4;i++){
makeWithdraw(10);
if(acc.getBalance()<10){System.out.println("insufficient balance");}
}
}
private synchronized void makeWithdraw(int amt){
if(acc.getBalance()>=amt){
System.out.println(Thread.currentThread().getName()+"\tis going to withdraw");
try{Thread.sleep(1000);}catch (Exception e){}
acc.withdraw(amt);
System.out.println("withdrawal is complete by"+Thread.currentThread().getName());
System.out.println("account balance is"+acc.getBalance());
}
else
{System.out.println("not enough balance for"+Thread.currentThread().getName());}
}

public static void main(String[] args){
demo d=new demo();
Thread one=new Thread(d,"lucy");
Thread two=new Thread(d,"fred");
one.start();
two.start();
}
};
Key points:
❑ synchronized methods prevent more than one thread from accessing an
object's critical method code simultaneously.
❑ You can use the synchronized keyword as a method modifier, or to start a
synchronized block of code.
❑ To synchronize a block of code (in other words, a scope smaller than the
whole method), you must specify an argument that is the object whose lock
you want to synchronize on.
❑ While only one thread can be accessing synchronized code of a particular
instance, multiple threads can still access the same object's unsynchronized code.
❑ When a thread goes to sleep, its locks will be unavailable to other threads.
❑ static methods can be synchronized, using the lock from the
java.lang.Class instance representing that class.

No comments:

Post a Comment