Am having difficulty in understanding how code given in Complete ref. of Java
This code works as stated in book;
value gets put by producer and consumed by consumer.
put:1
get:1
..so on..
how come book class gives no error ; as its using notify(),wait() functions of Thread class without extending it.
Next one is when we call producer(b); it goes in its constructor; which calls start ;taking execution in run() of it.. which calls put(i); in which while loop doesnt execute as value is set to false so by wait() it'll go to get and hence consumer will work 1st...so, where am i mistaking?
Code:
class book
{
int n;
boolean val=false;
synchronized int get()
{
while(!val)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Caught the exception"+e);
}
}
System.out.println("Got:"+n);
val=false;
notify();
return n;
}
synchronized void put(int n)
{
while(val)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Caught the exception"+e);
}
}
this.n=n;
val=true;
System.out.println("Put:"+n);
notify();
}
}
class producer implements Runnable
{
book b;
producer(book b)
{
this.b=b;
new Thread(b,"producer").start();
}
public void run()
{
int i=0;
while(true)
{
b.put(i++);
}
}
}
class consumer implements Runnable
{
book b;
consumer(book b)
{
this.b=b;
new Thread(this,"consumer").start();
}
public void run()
{
int i=0;
while(true)
{
b.get();
}
}
}
class PCfixed
{
public static void main(String a[])
{
book b=new book();
new producer(b);
new consumer(b);
System.out.println("Press control-c to stop!");
}
}
value gets put by producer and consumed by consumer.
put:1
get:1
..so on..
how come book class gives no error ; as its using notify(),wait() functions of Thread class without extending it.
Next one is when we call producer(b); it goes in its constructor; which calls start ;taking execution in run() of it.. which calls put(i); in which while loop doesnt execute as value is set to false so by wait() it'll go to get and hence consumer will work 1st...so, where am i mistaking?
Comment