user2546419
user2546419

Reputation: 65

Multithreading example from Head First java book .Please explain

class BankAccount
{
private int balance = 100;

public int getBalance()
{
    return balance;
}

public void withdraw(int amount)
{
    balance = balance - amount;
}
}
public class RyanAndMonicaJob implements Runnable{

private BankAccount account = new BankAccount();

public static void main(String[] args) {
    RyanAndMonicaJob theJob = new RyanAndMonicaJob();

    Thread one = new Thread(theJob);
    Thread two = new Thread(theJob);

    one.setName("Ryan");
    two.setName("Monica");

    one.start();
    two.start();
}

public void run()
{
    for(int x = 0;x < 10;x++)
    {
        makeWithdrawl(10);
        if(account.getBalance() < 10)
        {
            System.out.println("Overdrawn!");
        }
    }
}

public void makeWithdrawl(int amount)
{
    if(account.getBalance() >= amount)
    {
        System.out.println(Thread.currentThread().getName() + " is about to withdraw");
        try{
            System.out.println(Thread.currentThread().getName() + " is going to sleep");
            Thread.sleep(500);
        }
        catch(InterruptedException ex)
        {
            ex.printStackTrace();
        }

        System.out.println(Thread.currentThread().getName() + " woke up.");
        account.withdraw(amount);

        System.out.println(Thread.currentThread().getName() + " completes the withdrawl");

    }
    else
    {
        System.out.println("Sorry , not enough for " + Thread.currentThread().getName());
    }
}

}

In Head first Java book the output of the above example was:

The Output

See the third line of the ouput. That is the third line

Can this happen? That is can Monika start with waking up without outputting the withdrawl statement. Shouldn't the Monika thread also start with "Monika is about to withdraw".That is how can Monika thread start with "Monika woke up" statement.

I tried it in Netbeans and everytime I tried it , it started with the "Monika is about to withdraw statement". Then is the output given in the book wrong? If not can somebody please explain me this. Thanks again for your help.

Upvotes: 0

Views: 1355

Answers (1)

FrankM
FrankM

Reputation: 822

It's just that the image doesn't have the prints since the beginning. The for loop goes around 10 times. If you count back from the bottom for Monica tread you can see only only 7 and a half of the iterations.

"Sorry , not enough for Monica" is repeated 5 times

then the following lines that get intermingled with the Ryan ones when Monica thread goes to sleep count up 2 and a half iterations. "Monica is about to withdraw" "Monica is going to sleep" "Monica woke up." "Monica completes the withdrawl"

That means there was more output before this. It just didn't all fit on the console.

Upvotes: 1

Related Questions