Thursday, May 5, 2011

Example : Synchronization in Threads

package col.abc.test;

public class Lab4 {
public static void main(String[] args) {
Account acc = new Account();
new AccThread(acc);
new BccThread(acc);
}

}

class Account{

int bal = 970;

public synchronized void withDraw(int amt)
{
if(bal >= amt)
{
System.out.println(Thread.currentThread().getName() + " is going to withdraw... " + bal);
try {
Thread.sleep(1200);
} catch (Exception e) {
e.printStackTrace();
}
bal -= amt;
System.out.println(Thread.currentThread().getName() + " completed withdraw..." + bal);
}
else
{
System.out.println("No funds for " + Thread.currentThread().getName());
}
}

public int getBal() {
return bal;
}

}

class AccThread implements Runnable
{

Account acc = null;
AccThread(Account acc)
{
this.acc = acc;
Thread t1 = new Thread(this,"A");
t1.start();
}

@Override
public void run() {

for (int i = 0; i < 5; i++) {
acc.withDraw(225);
Thread.yield();
if(acc.getBal() < 0)
{
System.out.println("Amount is over drawn....");
}
}
}

}

class BccThread implements Runnable
{

Account acc = null;
BccThread(Account acc)
{
this.acc = acc;
Thread t2 = new Thread(this,"B");
t2.start();
}

@Override
public void run() {

for (int i = 0; i < 5; i++) {
acc.withDraw(225);
if(acc.getBal() < 0)
{
System.out.println("Amount is over drawn....");
}
}
}

}

No comments:

Post a Comment