PROGRAM:
class Q
{
int
n;
boolean
valueSet=false;
synchronized
int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException
caught");
}
System.out.println("Got :"+n);
valueSet=false;
notify();
return n;
}
synchronized
void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException
caught");
}
this.n=n;
valueSet=true;
System.out.println("put :"+n);
notify();
}
}
class Producer implements Runnable
{
Q
q;
Producer(Q
q)
{
this.q=q;
new
Thread(this,"Producer").start();
}
public
void run()
{
int i=0;
while(true)
{
q.put(i++);
}
}
}
class Consumer implements Runnable
{
Q
q;
Consumer(Q
q)
{
this.q=q;
new Thread(this,
"Consumer").start();
}
public
void run()
{
while(true)
{
q.get();
}
}
}
class PCmain
{
public
static void main(String arg[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press CtrlC
to stop.");
}
}
OUTPUT:
Press CtrlC to stop
Put
:0
Got
:0
Put
:1
Got
:1
Put
:2
Got
:2
Put
:3
Got
:3
Put
:4
Got
:4
Put
:5
Got
:5
Put
:6
Got
:6
Put
:7
Got
:7
Put
:8
Got
:8
Put
:9
Got
:9
Put
:10
Got
:10
Put
:11
Got
:11
No comments:
Post a Comment
Thanks for your valuable comments