Thread Sample - I

package banker;

/**
 *
 * @author Nurhak
 */
public class Banker extends Thread {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        Account a = new Account();
        Worker1 w1 = new Worker1("Worker1", a);
        Worker2 w2 = new Worker2("Worker2", a);
        w1.start();
        w2.start();
    }
}


package banker;

/**
 *
 * @author Nurhak
 */
public class Account {

    private double moneyAmount = 50;

    public double putMoneyToBank(double m) {
        this.moneyAmount += m;
        return moneyAmount;
    }

    public void getMoneyFromBank(double m) {
        if (this.moneyAmount < 0) {
            System.out.println("Not enough money at the Bank account! " + this.moneyAmount);
            return;
        }
        this.moneyAmount -= m;
    }

    public double learnMoneyAmount() {
        return moneyAmount;
    }
}

package banker;

/**
 *
 * @author Nurhak
 */
public class Worker1 extends Thread {

    Account a;

    public Worker1(String name, Account a) {
        super(name);
        this.a = a;
    }

    @Override
    public void run() {

        try {
            synchronized (a) {
                double amount = a.learnMoneyAmount();
                double firstAmount = amount;
                a.putMoneyToBank(100);
                sleep(1);
                a.putMoneyToBank(100);
                sleep(1);
                a.getMoneyFromBank(150);
                amount = a.learnMoneyAmount();

                System.out.println(currentThread().getName() + "-->" + firstAmount
                        + "+100+100-150 = " + amount);

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

package banker;

/**
 *
 * @author Nurhak
 */
public class Worker2 extends Thread {

    Account a;

    public Worker2(String name, Account a) {
        super(name);
        this.a = a;
    }

    @Override
    public void run() {

        try {
            synchronized (a) {

                double amount = a.learnMoneyAmount();
                double firstAmount = amount;
                a.putMoneyToBank(200);
                sleep(1);
                a.getMoneyFromBank(50);
                sleep(2);
                a.putMoneyToBank(100);
                amount = a.learnMoneyAmount();

                System.out.println(currentThread().getName() + "-->" + firstAmount
                        + " +200-50+100 = " + amount);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

Comments

Popular posts from this blog

Solution for "Can not obtain Oracle client information from registry"

Solution for the fault: "System.Diagnostics.Process.Start is not working on IIS, but working on ASP.NET Development Server"