class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
while(!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)
{
while(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 Synch
{
public static void main(String arg [])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("press control c to stop");
}
}
Output:-
got: 5803
put :5804
got: 5804
put :5805
got: 5805
put :5806
got: 5806
put :5807
got: 5807
put :5808
got: 5808
put :5809
got: 5809
put :5810
got: 5810
put :5811
got: 5811
put :5812
got: 5812
put :5813
got: 5813
put :5814
got: 5814
put :5815
got: 5815
put :5816
got: 5816
put :5817
got: 5817
put :5818
got: 5818
put :5819
got: 5819
put :5820
got: 5820
put :5821
got: 5821
put :5822
got: 5822
put :5823
got: 5823
C:\java\bin>
No comments:
Post a Comment