Static synchronization

     Static synchronization makes a single thread to execute the static method. Generally, this method deals with class level itself.

👉Why static synchronization?

 It provides the consistency for all objects in the class.

It ensures the other threads does not interfere the thread using static data.

Program:

This program creates a class with static member variable and static method.

In the main function, a single thread can access it at a time in class level, not object level.

class increment {

    static int inc = 0;

    // Static synchronized method

    public static synchronized void s_incre() {

        inc++;

        System.out.println("The value is incremented as " + inc);

    }

}

public class SampleCode {

    public static void main(String[] args) {

        // same function s_incre() is called by multiple threads

        Thread t1 = new Thread(() -> increment.s_incre());

        Thread t2 = new Thread(() -> increment.s_incre());

        Thread t3 = new Thread(() -> increment.s_incre());

        Thread t4 = new Thread(() -> increment.s_incre());

        t1.start();

        t2.start();

        t3.start();

        t4.start();

    }

}

Output:

C:\raji\blog>javac SampleCode.java

C:\raji\blog>java SampleCode

The value is incremented as 1

The value is incremented as 2

The value is incremented as 3

The value is incremented as 4

Try this same program with decrementing the value.

The code is given below.

class decrement {

    static int dec = 100;

    // Static synchronized method

    public static synchronized void s_decre() {

        dec--;

        System.out.println("The value is incremented as " + dec);

    }

}

public class SampleCode1 {

    public static void main(String[] args) {

        // same function s_incre() is called by multiple threads

        Thread t1 = new Thread(() -> decrement.s_decre());

        Thread t2 = new Thread(() -> decrement.s_decre());

        Thread t3 = new Thread(() -> decrement.s_decre());

        Thread t4 = new Thread(() -> decrement.s_decre());

        t1.start();

        t2.start();

        t3.start();

        t4.start();

    }

}

Output:

C:\raji\blog>javac SampleCode1.java

C:\raji\blog>java SampleCode1

The value is incremented as 99

The value is incremented as 98

The value is incremented as 97

The value is incremented as 96

That’s all. Two programs to illustrate static synchronization is done. Hope, this code is useful to you. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.