Synchronization :
we can use Synchronization in java as a modifier .it can be use as method level and block level but not in class level and variable level.
If multiple threads are trying to execute same java object simultaneously then there may be a chance of data inconsistency problem.
If we want to overcome these problem then we can use synchronized keyword in java.
The main advantage of synchronized keyword is overcome data inconsistency problem but there is a main disadvantage if synchronized keyword is it increase the waiting time of thread and creates a performance problem of threads.if we have no specific use until then there is a not recommended to use .
If multiple threads are trying to execute same java object simultaneously then there may be a chance of data inconsistency problem.
If we want to overcome these problem then we can use synchronized keyword in java.
The main advantage of synchronized keyword is overcome data inconsistency problem but there is a main disadvantage if synchronized keyword is it increase the waiting time of thread and creates a performance problem of threads.if we have no specific use until then there is a not recommended to use .
Synchronization implementation :
Synchronization in java is based on lock principle. in java every object has a unique lock,whenever we are trying to perform any operation in synchronization first think about lock.
If a thread object wants to execute synchronized method so he has to get lock of object,once he got a object then he able to perform synchronized method after execution automatically release the lock.
during execution any thread object wants to execute any other synchronized method so it is also required lock of object but lock has already occupy previous object so it is immediately go into the waiting state.
Example:in these example we declared methods as synchronized so we will get regular out put.
class Don
{
public synchronized void wish(String name)
{
for(int i=0;i<10;i++)
{
System.out.print("Have a nice day:");
try
{
Thread.sleep(2000);
}
catch(InterruptedException e){}
System.out.println(name);
}
}
}
class MyThread extends Thread
{
Don d;
String name;
MyThread(Don d,String name)
{
this.d=d;
this.name=name;
}
public void run()
{
d.wish(name);
}
}
class SynchronizedDemo
{
public static void main(String[] args)
{
Don d=new Don();
MyThread t1=new MyThread(d,"watson");
MyThread t2=new MyThread(d,"Smith");
t1.start();
t2.start();
}
}
output:
Have a nice day:watson
Have a nice day:watson
Have a nice day:watson
Have a nice day:watson
Have a nice day:watson
Have a nice day:watson
Have a nice day:watson
Have a nice day:watson
Have a nice day:watson
Have a nice day:watson
Have a nice day:Smith
Have a nice day:Smith
Have a nice day:Smith
Have a nice day:Smith
Have a nice day:Smith
Have a nice day:Smith
Have a nice day:Smith
Have a nice day:Smith
Have a nice day:Smith
Have a nice day:smith