Inter Thread Communication
// InterThread Communication
import java.io.*;
import java.util.Random;
class Que
{
int n;
boolean Flag = false;
int counter=0;
synchronized void put(int x)
{
while(Flag==true)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
this.n = x;
Flag=true;
notifyAll();
}
synchronized int get()
{
while(Flag==false)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
counter++;
if(counter==3)
{
Flag=false;
notify();
counter=0;
}
return this.n;
}
}
class Producer extends Thread
{
Que q;
Producer(Que obj)
{
super("PThd");
q = obj;
}
public void run()
{
int i = 0;
while(i<5)
{
Random rand = new Random();
int rn = rand.nextInt(100)%10;
q.put(rn);
System.out.println("Value sent = "+rn);
i++;
try{
this.sleep(500);
}
catch(Exception e)
{}
}
System.exit(0);
}
}
class Consumer1 extends Thread
{
Que q;
int sq;
Consumer1(Que obj)
{
super("CThd1");
q=obj;
this.setPriority(9);
}
public void run()
{
while(true)
{
int val = q.get();
System.out.println(this.getName()+" - Square = "+(val*val));
try{
this.sleep(500);
}
catch(Exception e)
{}
}
}
}
class Consumer2 extends Thread
{
Que q;
int cu;
Consumer2(Que obj)
{
super("CThd2");
q=obj;
this.setPriority(7);
}
public void run()
{
while(true)
{
int val = q.get();
System.out.println(this.getName()+" - Cube = "+(val*val*val));
try{
this.sleep(500);
}
catch(Exception e)
{}
}
}
}
class Consumer3 extends Thread
{
Que q;
int cu;
Consumer3(Que obj)
{
super("CThd3");
q=obj;
this.setPriority(5);
}
public void run()
{
while(true)
{
int val = q.get();
long fact=1;
for(int i=1;i<=val;i++)
fact=fact*i;
System.out.println(this.getName()+" - Factorial = "+fact);
try{
this.sleep(500);
}
catch(Exception e)
{}
}
}
}
class MultiThdPgm
{
public static void main(String as[])throws Exception
{
Que Q = new Que();
Producer P = new Producer(Q);
Consumer1 C1 = new Consumer1(Q);
Consumer2 C2 = new Consumer2(Q);
Consumer3 C3 = new Consumer3(Q);
P.start();
C1.start();
C2.start();
C3.start();
}
}
/*
sample output
>javac MultiThdPgm.java
>java MultiThdPgm
Value sent = 9
CThd1 - Square = 81
CThd2 - Cube = 729
CThd3 - Factorial = 362880
Value sent = 4
CThd1 - Square = 16
CThd2 - Cube = 64
CThd3 - Factorial = 24
Value sent = 5
CThd1 - Square = 25
CThd2 - Cube = 125
CThd3 - Factorial = 120
Value sent = 2
CThd1 - Square = 4
CThd2 - Cube = 8
CThd3 - Factorial = 2
Value sent = 3
CThd1 - Square = 9
CThd2 - Cube = 27
CThd3 - Factorial = 6
>
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu