Synchronization

Synchronization in Java is a capability to control the access of multiple threads to shared resources. This tutorial will teach you how to synchronize threads in Java.

Using Synchronized Methods

A synchronized method is used to lock an object for any shared resource:


class Table {
    synchronized void printTable(int n) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                Thread.sleep(400);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        final Table obj = new Table();
        
        Thread t1 = new Thread() {
            public void run() {
                obj.printTable(5);
            }
        };
        
        Thread t2 = new Thread() {
            public void run() {
                obj.printTable(100);
            }
        };
        
        t1.start();
        t2.start();
    }
}
      

Using Synchronized Blocks

A synchronized block can be used to lock an object for any shared resource:


class Table {
    void printTable(int n) {
        synchronized (this) {
            for (int i = 1; i <= 5; i++) {
                System.out.println(n * i);
                try {
                    Thread.sleep(400);
                } catch (Exception e) {
                    System.out.println(e);
                }
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        final Table obj = new Table();
        
        Thread t1 = new Thread() {
            public void run() {
                obj.printTable(5);
            }
        };
        
        Thread t2 = new Thread() {
            public void run() {
                obj.printTable(100);
            }
        };
        
        t1.start();
        t2.start();
    }
}
      

Static Synchronization

Static synchronization is used to synchronize class-level shared resources:


class Table {
    synchronized static void printTable(int n) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(n * i);
            try {
                Thread.sleep(400);
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t1 = new Thread() {
            public void run() {
                Table.printTable(5);
            }
        };
        
        Thread t2 = new Thread() {
            public void run() {
                Table.printTable(100);
            }
        };
        
        t1.start();
        t2.start();
    }
}
      

Continue exploring our intermediate tutorials to learn more about Java programming.

Scroll to Top