Sunday, May 1, 2016

Producer-Consumer with java.util.concurrent.locks.Lock

In my earlier post I have given odd-even printing in sequence using 2 threads.(Similar to producer consumer). In this post I have given implementation of producer consumer problem with java.util.concurrent.locks.Lock

Code:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class MyPCWithLock {
public static void main(String[] args) {
SharedResourceMgr srm=new SharedResourceMgr();
Thread t1=new Thread(new ProducerWithLock(srm));
Thread t2=new Thread(new ConsumerWithLock(srm));
t1.start();
t2.start();
}
}

class SharedResourceMgr{
Lock lock=new ReentrantLock();;
Condition condition=lock.newCondition();
boolean produced=false;
public void consume(){
lock.lock();
try{
while(!produced){
condition.await();
}
System.out.println("Consumed..");
produced=false;
condition.signalAll();
}catch (Exception e) {
// TODO: handle exception
}finally{
lock.unlock();
}
}

public void produce(){
lock.lock();
try{
while(produced){
condition.await();
}
System.out.println("Produced..");
produced=true;
condition.signalAll();//very important, it should not be notify
}catch (Exception e) {
// TODO: handle exception
}finally{
lock.unlock();
}
}

}

class ProducerWithLock implements Runnable{
SharedResourceMgr srm;
ProducerWithLock(SharedResourceMgr s){
this.srm=s;
}
@Override
public void run() {
for(int i=0;i<5;i++){
//System.out.println("P:"+i);
srm.produce();
try{
Thread.sleep(1000);
}catch(Exception ex){

}
}
}
}
class ConsumerWithLock implements Runnable{
SharedResourceMgr srm;
ConsumerWithLock(SharedResourceMgr s){
this.srm=s;
}
@Override
public void run() {
for(int i=0;i<5;i++){
//System.out.println("C:"+i);
srm.consume();
try{
Thread.sleep(1000);
}catch(Exception ex){

}
}
}
}

Output:
Produced..
Consumed..
Produced..
Consumed..
Produced..
Consumed..
Produced..
Consumed..
Produced..
Consumed..

No comments:

Post a Comment