Java Synchronization


When two or more threads access the shared resource which makes ensure that only one thread can access the resource at a time. This process is called synchronization.

 synchronized(object) {
// statements to be synchronized
}

Advantage of Synchronization

  • It is used to prevent thread interference and consistency problem.

Synchronized Methods

When a thread is inside a synchronized method, all other threads that tries to call any other synchronized method on the same instance have to wait.

 

Synchronized method is used to lock an object for any shared resource.


Example:

Multithreading example without synchronization

class Calculate {
		void show(int n) {
        try {
            for(int i=1;i<=3;i++){  
                System.out.println(n*i);
                Thread.sleep(500);
            }
        } catch(InterruptedException e) {
            System.out.println("Interrupted");
        }
    }
}
class Data implements Runnable {
    int n;
    Calculate ca;
    Thread t;
    public Data(Calculate c, int num) {
        ca = c;
        n = num;
        t = new Thread(this);
        t.start();
    }
    public void run() {
        ca.show(n);
    }
}
public class WithoutSynchronization{
    public static void main(String args[]) {
        Calculate ca = new Calculate();
        Data d1= new Data(ca, 10);
        Data d2= new Data(ca, 100);
        try {
            d1.t.join();
            d2.t.join();
        } catch(InterruptedException e) {
            System.out.println("Interrupted");
        }
    }
} 

Example:

Multithreading example with synchronization

class Calculate {
    synchronized void show(int n) {
        try {
            for(int i=1;i<=3;i++){  
                System.out.println(n*i);
                Thread.sleep(500);
            }
        } catch(InterruptedException e) {
            System.out.println("Interrupted");
        }
    }
}
class Data implements Runnable {
    int n;
    Calculate ca;
    Thread t;
    public Data(Calculate c, int num) {
        ca = c;
        n = num;
        t = new Thread(this);
        t.start();
    }
    public void run() {
        ca.show(n);
    }
}
public class Synchronization{
    public static void main(String args[]) {
        Calculate ca = new Calculate();
        Data d1= new Data(ca, 10);
        Data d2= new Data(ca, 100);
        try {
            d1.t.join();
            d2.t.join();
        } catch(InterruptedException e) {
            System.out.println("Interrupted");
        }
    }
} 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.