Understanding Thread in Java

Account.java

package thread;

public class Account {
    private int balance=50;

    public int getBalance() {
        return balance;
    }

    public void withDraw(int amt){
        balance-=amt;
    }
}

Output

BankClass.java

package thread;

public class BankClass implements Runnable{

    Account account = new Account();

    public static void main(String[] args) {
        BankClass bankClass = new BankClass();
        Thread t1 = new Thread(bankClass,"Taher");
        Thread t2 = new Thread(bankClass,"Tinwala");
        t1.start();
        t2.start();
    }

    public void run() {
        for (int i = 0; i < 5; i++) {
            if(account.getBalance()>=10){
                try {
                System.out.println(Thread.currentThread().getName()+" is withdrawing... currBalance : "+account.getBalance());                
                account.withDraw(10);
                Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    System.out.println(ex);
                }
                System.out.println(Thread.currentThread().getName()+" is completed... currBalance : "+account.getBalance());
            }else{
                System.out.println("Not enough balance "+Thread.currentThread().getName()+" currBalance : "+account.getBalance());
            }
            if(account.getBalance()<0){
                System.out.println("Overdrawn ... currBalance : "+account.getBalance());
            }
        }
    }
}

OutPut

Taher is withdrawing... currBalance : 50
Tinwala is withdrawing... currBalance : 40
Tinwala is completed... currBalance : 30
Taher is completed... currBalance : 30
Tinwala is withdrawing... currBalance : 30
Taher is withdrawing... currBalance : 30
Tinwala is completed... currBalance : 10
Taher is completed... currBalance : 10
Tinwala is withdrawing... currBalance : 10
Taher is withdrawing... currBalance : 10
Tinwala is completed... currBalance : -10
Overdrawn ... currBalance : -10
Not enough balance Tinwala currBalance : -10
Overdrawn ... currBalance : -10
Not enough balance Tinwala currBalance : -10
Overdrawn ... currBalance : -10
Taher is completed... currBalance : -10
Overdrawn ... currBalance : -10
Not enough balance Taher currBalance : -10
Overdrawn ... currBalance : -10
Not enough balance Taher currBalance : -10
Overdrawn ... currBalance : -10
Advertisements
This entry was posted in Core JAVA, Just 4 Knowledge. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s