At a time first thread complication and after second thread run is called synchronization. Synchronization in java is the capability to control the access of multiple threads to any shared resource.

Java Synchronization is better option where we want to allow only one thread to access the shared resource.

Java provides a way of creating threads and synchronizing their task by using synchronized blocks. Synchronized blocks in Java are marked with the synchronized keyword. A synchronized block in Java is synchronized on some object. All synchronized blocks synchronized on the same object can only have one thread executing inside them at a time. All other threads attempting to enter the synchronized block are blocked until the thread inside the synchronized block exits the block.

Example -

class Demo{
synchronized void display(){
for(int i=1; i<=5; i++){
try{
System.out.print(Thread.currentThread().getName()+" "+i);
Thread.sleep(1000);
}
catch(InterruptedException e){
}
}
}
}
class TDemo implements Runnable{
Thread t;
static Demo d=new Demo();
TDemo(String s){
t=new Thread(this,s);
t.start();
}
public void run(){
d.display();
}
}
class Synchronization{
public static void main(String []arr){
TDemo t1=new TDemo("First");
TDemo t2=new TDemo("Second");
}
}

Example -

class Demo{
synchronized void display(){
for(int i=1; i<=5; i++){
try{
System.out.print(Thread.currentThread().getName()+" "+i);
Thread.sleep(1000);
}
catch(InterruptedException e){
}
}
}
}
class TDemo implements Runnable{
Thread t;
Demo d;
TDemo(String s,Demo d){
t=new Thread(this,s);
this.d=d;
t.start();
}
public void run(){
d.display();
}
}
class Synchronization{
public static void main(String []arr){
Demo d=new Demo();
TDemo t1=new TDemo("First",d);
TDemo t2=new TDemo("Second",d);
}
}