Professional Documents
Culture Documents
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?"};
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();
}
}
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);
}
}