Saturday, 10 June 2017

Java Tutorial: Java Threads (Inter thread communication in java | java inter thread communication) ~ foundjava


Click here to watch in Youtube :
https://www.youtube.com/watch?v=-CUL0--zfrM&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial: Java Threads (Inter thread communication in java | java inter thread communication) 
Java Tutorial: Java Threads (Inter thread communication in java | java inter thread communication) 
Java Tutorial: Java Threads (Inter thread communication in java | java inter thread communication) 
Java Tutorial: Java Threads (Inter thread communication in java | java inter thread communication) 
Java Tutorial: Java Threads (Inter thread communication in java | java inter thread communication) 
Java Tutorial: Java Threads (Inter thread communication in java | java inter thread communication) 

InterthreadCommunitcationDemo.java
class InterthreadCommunitcationDemo
{
    public static void main(String args[])
    {
        final BankAccount bankAccount = new BankAccount();
        
        new Thread("Thread 1")
        {
            public void run()
            {
                bankAccount.withdraw(50000);
            }
        }.start();
        
        new Thread("Thread 2")
        {
            public void run()
            {
                bankAccount.deposit(80000);
            }
        }.start();

    }
}
BankAccount.java
class BankAccount
{
    private int amount = 10000;

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

        if (this.amount < amount)
        {
            System.out.println("Less balance; waiting for deposit...");
            try
            {
                wait();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        this.amount -= amount;
        System.out.println("Withdraw completed...");
    }

    synchronized void deposit(int amount)
    {
        System.out.println("Going to deposit...");
        this.amount += amount;
        System.out.println("Deposit completed... ");
        notify();
    }
}
Output
Going to withdraw...
Less balance; waiting for deposit...
Going to deposit...
Deposit completed... 
Withdraw completed...
Refer: 
https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Object.html

Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment