I have one small sample code for synchronization
test.
**************************Account.java***************
public class Account
{
private int balance=50;
public int getBalance(){
return balance;
}
public void withdraw(int amt){
balance=balance-amt;
}
}
*********************AccountJob.java******************
public class AccountJob implements Runnable
{
private Account account;
public static final int MIN_BALANCE=10;
public static final int WID_BALANCE=10;
public AccountJob(Account account){
this.account=account;
}
public void run(){
for(int i=0;i<5;i++){
withdraw();
}
}
private synchronized void withdraw(){
//------check for balance if >= 10 go on.
if(account.getBalance() >= MIN_BALANCE){System.out.println(Thread.currentThread().getName()+" is going to withdraw ");
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
account.withdraw(WID_BALANCE);
System.out.println(Thread.currentThread().getName()+" completes withdraw.");
}
else{
System.out.println("Not enough balance in "+Thread.currentThread().getName()+"'s account, balance is"+account.getBalance());
}
}
}
**********************TestAccount.java********************
public class TestClass{
public static void main(
String[] args){
Account account=new Account();
// both runnable objects refer to same Account object
// but here two threads have different runnable object.
Thread thread1=new Thread(new AccountJob(account));
Thread thread2=new Thread(new AccountJob(account));
thread1.setName("Fred");
thread2.setName("Lucy");
thread1.start();
thread2.start();
}
}
***************************************************************
Problem:
in TestAccount class this code
Thread thread1=new Thread(new AccountJob(account));
Thread thread2=new Thread(new AccountJob(account));
i am passing to different objects to two different threads.
and also the method in AccountJob class
private synchronized void withdraw(){
is synchronized.
BUT im not getting the synchronized behavior.
two threads are withdrawing balance below 0.while it should not because the method for withdrawal is SYNCHRONIZED.
but if instead of that i try this thing in TestAccount class
code: AccountJob accountJob=new AccountJob(account);
// same object reference in two threads
Thread thread1=new Thread(accountJob);
Thread thread2=new Thread(accountJob);
Output: synchronization works
instead of current code which is
code:
//different runnable objects.
Thread thread1=new Thread(new AccountJob(account));
Thread thread2=new Thread(new AccountJob(account));
Output: Account overdrawn synchronization doesn't work.
Can any one tell me
1)is this problem due to two different objects of Runnable
2)if yes then WHY.
waiting for answer.
Thaks for reply.