Write a Thread program in which producer will produce 5 characters from a character array & receiver will receive them without missing any character. The character will be produced & received one by one. ( File must be save as: PCF2.java)
class Q
{
char n;
int v = 1;
synchronized void get()
{
if(v==1)
try
{
wait();
} catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
v = 1;
notify();
}
synchronized void put(char n)
{
if(v==0)
try
{
wait();
} catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
this.n = n;
v = 0;
System.out.println("Put: " + n);
notify();
}
}
class Producer extends Thread
{
Q q;
char a[]={'a','b','c','d','e','f','g','h','i','j'};
Producer(Q q)
{
this.q = q;
start();
}
public void run()
{
int i = 0;
while(i<10)
{
q.put(a[i++]);
}
}
}
class Consumer extends Thread
{
Q q;
Consumer(Q q)
{
this.q = q;
start();
}
public void run()
{
int i=0;
while(i<10)
{
i++;
q.get();
}
}
}
class Assignment16
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
}
}
////////////////////////////////////////////
Copy & paste this code in your Textpad & run, then you will get output.......
If you have any problem please comment below.........
Copy & paste this code in your Textpad & run, then you will get output.......
If you have any problem please comment below.........