Menu
Topics Index
...
`

Static Synchroniztion - Java Example Program


Static Synchroniztion
class ATMTransaction
{
    public static void main(String[] args)
    {
        for (int i = 1; i < 4; i++)
        {
            AccountHolder t = new AccountHolder(); // LINE A
            t.setName("Person" + i);
            t.start();
        }
    }
}

class ATMCenter
{

    static synchronized void userAction()
    {
        System.out.println(Thread.currentThread().getName() + " entered"); // LINE D
        System.out.println("Performed Transaction");
        try
        {
            Thread.sleep(400);
        }
        catch (Exception e)
        {
            System.out.println("Thread Interrupted");
        }
        System.out.println(Thread.currentThread().getName() + " transaction complete");
        System.out.println(Thread.currentThread().getName() + " leaving......."); // LINE E
        System.out.println("-----------------------------------------------");
    }
}

class AccountHolder extends Thread
{

    //ATMCenter s = new ATMCenter(); // LINE F

    @Override
    public void run()
    {
        //s.userAction(); // LINE G
        ATMCenter.userAction();
    }
}
OUTPUT

Person1 entered
Performed Transaction
Person1 transaction complete
Person1 leaving.......
-----------------------------------------------
Person3 entered
Performed Transaction
Person3 transaction complete
Person3 leaving.......
-----------------------------------------------
Person2 entered
Performed Transaction
Person2 transaction complete
Person2 leaving.......
-----------------------------------------------

DESCRIPTION

In the above program we have three classes ATMTransaction which is the main class, ATMCenter which synchronizes the objects of the AccountHolder, AccountHolder which creates threads(AccountHolder objects). In the main method at LINE A we have created three threads(Person1, Person2 and Person3) by using AccountHolder. At LINE B we are invoking the start method for each thread in the for loop. At LINE C in the run method we are invoking the userAction method. Since userAction method is a static method we invoke it with class name. In the userAction we are printing the statements user entered and user leaving at LINE D and LINE E. Here in the program we used static synchronized for userAction. so no two objects of AccountHolder will access the userAction method so it prints the following output.

THINGS TO TRY
  • Un comment the commented lines in the run method and make the userAction to non-static (At LINE F we are creating a new object to ATMCenter each time when an AccountHolder is created and invoking userAction on AccountHolder object at LINE G). Since the method is non-static it will produce a different output.

© meritcampus 2019

All Rights Reserved.

Open In App