Aim:
Source Code:
ProducerConsumer.java
// create a class
class Items
{
int count = 1000;
synchronized void consume(int cnt)
{
System.out.println("Items :"+this.count);
System.out.println("Consumer : Going to consume "+cnt);
if (this.count < cnt)
{
System.out.println("Low : waiting for produce..");
try
{
Thread.sleep(10000);
wait();
}
catch (InterruptedException e)
{ }
}
this.count = this.count - cnt;
System.out.println("consume competed");
System.out.println("Current :"+this.count);
}
synchronized void produce(int cnt)
{
System.out.println("Producer : Going to produce "+cnt);
this.count = this.count + cnt;
System.out.println("Current :"+this.count);
System.out.println("produce Completed");
notify();
}
}
// creating a Thread1
class Consumer extends Thread
{
Items pt;
Consumer(Items pt)
{
this.pt = pt;
}
public void run()
{
pt.consume(1500);
}
}
// creating a Thread2
class Producer extends Thread
{
Items pt;
Producer(Items pt)
{
this.pt = pt;
}
public void run()
{
pt.produce(800);
}
}
// main class
class ProducerConsumer
{
public static void main(String[] args)
{
Items obj = new Items();
Consumer t1 = new Consumer(obj);
Producer t2 = new Producer(obj);
t1.start();
t2.start();
}
}
Output:
Related Content :