You are on page 1of 7

Exercise 23

1. Write a program to demonstrate the chat between two friends using interthread
communication. One friend can not send the another message before getting the
answer of previous message.
Ans.
class ChitChat
{
boolean flag = false;
synchronized void Question(String q)
{
if(flag)
{
try
{
wait();
}
catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
}
System.out.println(q);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
flag=true;
notify();
}
synchronized void Answer(String a)
{
if(!flag)
{
try
{
wait();
}
catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
}
System.out.println(a);
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
System.out.println(ex.getMessage());
}
flag=false;
notify();
}
}
class Thread1 extends Thread
{
ChitChat c1;
Thread1(ChitChat c)
{
c1=c;
}
public void run()
{
String Q[] = {"Hello","How are you?","I am also Fine!","How was your day?","Why
so?"};

for(int i=0; i<Q.length;i++)


c1.Question(Q[i]);
}
}
class Thread2 extends Thread
{
ChitChat c2;
Thread2(ChitChat c)
{
c2=c;
}
public void run()
{
String A[] = {"Hello","I am Fine! What about you?","Good","very bad","bcz of Java
LAb "};

for(int i=0; i<A.length;i++)


c2.Answer(A[i]);
}
}

class InterThreadC
{
public static void main(String args[])
{
ChitChat c =new ChitChat();
Thread t1 =new Thread1(c);
Thread t2 =new Thread2(c);

t1.start();
t2.start();
}
}

2. Write a program to implement withdrawal and deposit functions of banking. Both


functions have a common information balance. If the balance is low than expected
withdrawal amount it should wait for deposit than withdrawal function should be
completed.
Ans.
class Account {
public int balance;
public int accountNo;
void displayBalance() {
System.out.println("Account No : " + accountNo + " Balance : " + balance);
}

synchronized void deposit(int amount){


balance = balance + amount;
System.out.println( amount + " is deposited");
displayBalance();
}

synchronized void withdraw(int amount){


balance = balance - amount;
System.out.println( amount + " is withdrawn");
displayBalance();
}
}

class TransactionDeposit implements Runnable{


int amount;
Account accountX;
TransactionDeposit(Account x, int amount){
accountX = x;
this.amount = amount;
new Thread(this).start();
}

public void run(){


accountX.deposit(amount);
}
}

class TransactionWithdraw implements Runnable{


int amount;
Account accountY;

TransactionWithdraw(Account y, int amount) {


accountY = y;
this.amount = amount;
new Thread(this).start();
}

public void run(){


accountY.withdraw(amount);
}
}

class Ex23p2
{
public static void main(String args[]) {
Account ABC = new Account();
ABC.balance = 1000;
ABC.accountNo = 236;
TransactionDeposit t1;
TransactionWithdraw t2;
t1 = new TransactionDeposit(ABC, 600);
t2 = new TransactionWithdraw(ABC,900);
}
}

You might also like