Menu
Topics Index
...
`

InterThreadDemo - Java Example Program


InterThreadDemo
class InterThreadDemo
{
    public static void main(String arg[])
    {
        final Customer c = new Customer();
        new Thread()
        {
            public void run()
            {
                c.withdraw(15000);
            }
        }.start();
        new Thread()
        {
            public void run()
            {
                c.deposit(10000);
            }
        }.start();
        new Thread()
        {
            public void run()
            {
                c.deposit(10000);
            }
        }.start();    
    }
}

class Customer
{
    int amount = 10000;

    synchronized void withdraw(int amount)
    {
        System.out.println("Available Balance " + this.amount);
        System.out.println("Going to withdraw." + amount);

        if (this.amount < amount)
        {
            System.out.println("Insufficient Balance waiting for deposit.");
            try
            {
                wait();
            } catch (Exception e)
            {
                System.out.println("Interruption Occured");
            }
        }
        this.amount -= amount;
        System.out.println("Detected amaount: " + amount);
        System.out.println("Balance amount : " + this.amount);
    }

    synchronized void deposit(int amount)
    {
        System.out.println("Going to deposit " + amount);
        this.amount += amount;
        System.out.println("Available Balance " + this.amount);
        System.out.println("Transaction completed.\n");
        notify();
    }
}
OUTPUT

Available Balance 10000
Going to withdraw.15000
Insufficient Balance waiting for deposit.
Going to deposit 10000
Available Balance 20000
Transaction completed.

Detected amaount: 15000
Balance amount : 5000
Going to deposit 10000
Available Balance 15000
Transaction completed.

DESCRIPTION

In the above program we have shown threads communicate and we have shown how to wait and notify methods. In the above program we have two classes customer class and Test class. In the Customer class we have two methods one will deposit amount in the customer account and one for withdraw. We created one object for Customer class which is final and created three threads to access the methods. In the above example two methods are synchronized so that no two threads can access the same method at same time.

THINGS TO TRY
  • Create a thread and withdraw 15000 and see the output the threads goes to wait state until a deposit takes place.
  • Create a thread and deposit 5000 and see the output the thread awakes and completes it's execution.

© meritcampus 2019

All Rights Reserved.

Open In App