As I am new to Java Threads, I was just experimenting with my code. From Kathy' Sierra SCJP book, I learnt about thread.join()
method. Then I learnt 'bout Synchronization
. Below is the code in which I used thread.join()
method instead of making makeWithdrawal()
method a synchronized
.
AccountDanger class:
public class AccountDanger implements Runnable{
private Account acct=new Account();
public static void main(String args[])throws InterruptedException{
AccountDanger r=new AccountDanger();
Thread one=new Thread(r);
Thread two=new Thread(r);// unable to start
one.setName("Fred");
two.setName("Lucy");
one.start();
one.join();// used join() instead of using synchronize keyword.
two.start();// unable to start
}
public void run(){
for(int x=0;x<5;x++){
makeWithdrawal(10);
if(acct.getBalance()<0){
System.out.println("Account is over-drawn");
}
}
}
private void makeWithdrawal(int amt){
if(acct.getBalance()>=amt){
System.out.println(Thread.currentThread().getName()+" is goint to withdraw");
try{
Thread.sleep(500);
}
catch(InterruptedException ex){}
acct.withdraw(amt);
System.out.println(Thread.currentThread().getName()+" completes the withdrawal");
}
else{
System.out.println("Not enough in account for "+Thread.currentThread().getName()+" to withdraw "+acct.getBalance());
}
}
}
Account class:
class Account{
private int balance=50;
public int getBalance(){
return balance;
}
public void withdraw(int amount){
balance=balance-amount;
}
}
But after seeing the output (more than 10 times), I realized that I was unable to start my second thread (thread with the name Lucy
). Actually, after testing with two.isAlive()
print statement, I found it to be alive. But why can't i see this Lucy
thread working? Why is that? can any one help me? Below is the output I get always get:
Fred is goint to withdraw
Fred completes the withdrawal
Fred is goint to withdraw
Fred completes the withdrawal
Fred is goint to withdraw
Fred completes the withdrawal
Fred is goint to withdraw
Fred completes the withdrawal
Fred is goint to withdraw
Fred completes the withdrawal
Not enough in account for Lucy to withdraw 0
Not enough in account for Lucy to withdraw 0
Not enough in account for Lucy to withdraw 0
Not enough in account for Lucy to withdraw 0
Not enough in account for Lucy to withdraw 0