| Author |
please see the output of the code but i m expecting some other output
|
pi gupta
Greenhorn
Joined: Jun 24, 2012
Posts: 3
|
|
Code:
class Account{
private int amtBalance;
public synchronized void debitAmount(int amount){
try{
System.out.println("Checking Balance");
while(amtBalance-amount<0){
System.out.println("Not hav enough balance");
wait();
}
System.out.println("debiting");
amtBalance-=amount;
}
catch(Exception e){
}
}
public synchronized void creditAmount(int amount){
amtBalance+=amount;
System.out.println("balance:" + amtBalance + "Notify");
notify();
}
}
class Thread1 extends Thread{
Account ac;
Thread1(Account ac){
this.ac=ac; }
public void run()
{
ac.debitAmount(300);
}
}
class Thread2 extends Thread{
Account ac;
Thread2(Account ac){
this.ac=ac; }
public void run()
{
int i=100;
while(i<=300){
ac.creditAmount(100);
i+=100;
}
}
}
public class ThreadMain{
public static void main(String []args){
Account ac=new Account();
Thread1 th1=new Thread1(ac);
th1.start();
Thread2 th2=new Thread2(ac);
th2.start();
}
}
Output:
Checking Balance
Not hav enough balance
balance:100Notify
balance:200Notify
balance:300Notify
debiting
my expected output:
Checking Balance
Not hav enough balance
balance:100Notify
Not hav enough balance
balance:200Notify
Not hav enough balance
balance:300Notify
debiting
Please reply i am not getting my expected output
Thanks in advance
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16692
|
|
pi gupta wrote:Code:
Output:
Checking Balance
Not hav enough balance
balance:100Notify
balance:200Notify
balance:300Notify
debiting
my expected output:
Checking Balance
Not hav enough balance
balance:100Notify
Not hav enough balance
balance:200Notify
Not hav enough balance
balance:300Notify
debiting
Please reply i am not getting my expected output
Thanks in advance
Sending a notification doesn't automatically do a context switch back to the waiter -- in your case, the crediting thread has enough of the time slice to fully credit the account up to 300, before the debit thread woke up from the notification.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
pi gupta
Greenhorn
Joined: Jun 24, 2012
Posts: 3
|
|
Thanks Henry,
But how can i know about the time slice..
is it platform dependent???
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16692
|
|
pi gupta wrote:Thanks Henry,
But how can i know about the time slice..
is it platform dependent???
With the current JVMs, I believe they are all integrated with the native threading system -- hence, yes, scheduling is platform dependent.
Henry
|
 |
pi gupta
Greenhorn
Joined: Jun 24, 2012
Posts: 3
|
|
Thanks Henry
|
 |
 |
|
|
subject: please see the output of the code but i m expecting some other output
|
|
|