Synchronization in Threads
// Synchronization in Threads
// Inter Thread Communication
class Que
{
int N;
boolean Flag = false;
synchronized public int get() // int mtd void
{
while(!Flag)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
System.out.println("Consumed = "+N);
Flag = false;
notify();
return N;
}
synchronized void put(int n) // void mtd int
{
while(Flag) //2
{
try
{
wait();
}
catch(Exception e)
{
System.out.println(e);
}
}
this.N = n; //3
System.out.println("Produced = "+N);
Flag = true; //4
notify();
}
}
class Producer extends Thread
{
Que Q;
Producer(Que q)
{
super("PT");
this.Q = q;
}
public void run()
{
for(int i=1;i<=5;i++)
Q.put(i);
}
}
class Consumer extends Thread
{
Que Q;
Consumer(Que q)
{
super("CT");
this.Q = q;
}
public void run()
{
for(int i=1;i<=5;i++)
Q.get();
}
}
class PC
{
public static void main(String as[])
{
Que q = new Que();
Producer p = new Producer(q);
Consumer c = new Consumer(q);
p.start();
c.start();
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu