Wednesday, 16 August 2017

Multithreading producer consumer problem

// Implement solution of producer consumer problem.

import java.util.LinkedList;

public class Threadexample
{
    private static volatile int x=0;
    private static boolean isAvailable=false;
public static void main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();

// Create producer thread
Thread t1 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Create consumer thread
Thread t2 = new Thread(new Runnable()
{
@Override
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Start both threads
t1.start();
t2.start();

// t1 finishes before t2
t1.join();
t2.join();
}

// This class has a list, producer (adds items to list
// and consumber (removes items).
public static class PC
{

public void produce() throws InterruptedException
{

while (true)
{
synchronized (this)
{

                                       if(isAvailable)
                                       wait(); // wait until consumer finished
                   
                                       x++;
                                       System.out.println("Producer Produced "+x);
                                        isAvailable=true;
// notifies the consumer thread that
// now it can start consuming
notify();

// makes the working of program easier
// to understand
Thread.sleep(500);
}
}
}

// Function called by consumer thread
public void consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{

                                        if(!isAvailable)
                                         wait();
                         System.out.println("Consumer consumed-"
+ x);
                                         isAvailable=false;
// Wake up producer thread
notify();

// and sleep
Thread.sleep(500);
}
}
}
}
}

No comments:

Post a Comment