Design a thread-safe implementation of Queue class. Write a multi-threaded producer-consumer application that uses this Queue class.

import java.io.*;
class queue
{
int n;
boolean v=false;
synchronized int get()
{
if(!v)
try
{
wait();
}
catch(InterruptedException e){}
System.out.println("GOT:"+n);
v=false;
notify();
return n;
}
synchronized void put(int n)
{
if(v)
try
{
wait();
}
catch(InterruptedException e){}
this.n=n;
v=true;
System.out.println("put:"+n);
notify();
}
}
class prod implements Runnable
{
queue q;
int n;
prod(queue q,int n)
{
this.q=q;
this.n=n;
new Thread(this,"producer").start();
}
public void run()
{
int i=1;
while(i<=n)
{
try
{
Thread.sleep(1000);
q.put(i++);
}
catch(InterruptedException e)
{}
}
System.exit(0);
}
}
class cons implements Runnable
{
queue q;
cons(queue q)
{
this.q=q;
new Thread(this,"consumer").start();
}
public void run()
{
while(true)
{
try
{
Thread.sleep(1000);
q.get();
}
catch(InterruptedException e){}
}}}
class nprod
{
public static void main(String args[])throws IOException
{
DataInputStream in=new DataInputStream(System.in);
System.out.println("enter the buffer size");
int a=Integer.parseInt(in.readLine());
queue q=new queue();
new prod(q,a);
new cons(q);
}
}

Output:

C:\j2sdk1.4.0\bin>javac nprod.java
Note: nprod.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.

C:\j2sdk1.4.0\bin>java nprod
Enter the Buffer size
5
PUT:1
GOT:1
PUT:2
GOT:2
PUT:3
GOT:3
PUT:4
GOT:4
PUT:5
GOT:5

1 comment:

Retrospect said...

Thankyou for all the details and the help. This is seriously very helpful. I also found some free CSE practice tests for GATE exams. Here is the the webpage link: http://thegateacademy.com/gate-free-test/