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 1 = new thread(thejob);     thread 2 = 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() + " withdraw");         try{             system.out.println(thread.currentthread().getname() + " going 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 withdrawl");      }     else     {         system.out.println("sorry , not enough " + thread.currentthread().getname());     } }  } 

in head first java book output of above example was:

the output

see third line of ouput. the third line

can happen? can monika start waking without outputting withdrawl statement. shouldn't monika thread start "monika withdraw".that how can monika thread start "monika woke up" statement.

i tried in netbeans , everytime tried , started "monika withdraw statement". output given in book wrong? if not can please explain me this. again help.

it's image doesn't have prints since beginning. loop goes around 10 times. if count bottom monica tread can see only 7 , half of iterations.

"sorry , not enough monica" repeated 5 times

then following lines intermingled ryan ones when monica thread goes sleep count 2 , half iterations. "monica withdraw" "monica going sleep" "monica woke up." "monica completes withdrawl"

that means there more output before this. didn't fit on console.


Comments

Popular posts from this blog

php - Invalid Cofiguration - yii\base\InvalidConfigException - Yii2 -

How to show in django cms breadcrumbs full path? -

ruby on rails - npm error: tunneling socket could not be established, cause=connect ETIMEDOUT -