Вы находитесь на странице: 1из 2

//Lab program normal queue Inter thread communication

import java.util.*;
class Q {
int queue[]=new int[3],rear=-1,front=-1;
boolean full= false,empty=true;
synchronized void get()
{
while(empty)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + queue[front]);
if(front==rear )
{
rear=-1;
front=-1;
empty=true;
}
else
front = front+1;

if(rear<queue.length-1)
full=false;
notify();
}
synchronized void put(int n)
{
Scanner obj=new Scanner(System.in);
System.out.println("full"+full);
while(full)
try
{ wait(); }
catch(InterruptedException e)
{ System.out.println("InterruptedException caught"); }
rear = rear+1;
if(front==-1) front++;
queue[rear]=n;
System.out.println("Put : "+n);
empty=false;
if (rear ==queue.length-1)
full=true;
notify();
}
}

class Producer implements Runnable


{
Q q;
Producer(Q q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{
for (int i=1; ; i++)
{
try
{
q.put(i);
if(i==q.queue.length)
i=0;
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
System.out.println(ex);
}
}
}
}

class Consumer implements Runnable


{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
for(int i=1; ; i++)
{
try
{
q.get();
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
System.out.println(ex);
}
}
}
}

class LabQueue1
{
public static void main(String args[])
{
Q q = new Q();
new Consumer(q);
new Producer(q);
}
}

Вам также может понравиться