OneCompiler

java code prolem

287

import java.io.;
import java.util.
;
class Q
{
int n;
bollean valueset=false;
synchronized int get()
{
while(!valueset)
try{
wait();
}catch(InterruptedException e)
{
System.out.println("Interrupted Exception 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("Interrupted caught");
}
this.n=n;
valueset=true;
System.out.println("put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(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)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{

 while(true)
   {
     q.get();
   }

}
}
class Example122
{
public static void main(String args[])
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press controle+c to stop");
}
}