package com.cjw.concurrent.scxf.lock;
import com.cjw.dto.goods.GoodsDto;
import lombok.extern.slf4j.Slf4j;
import java.util.Date;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author wucj
* @date 2019-06-27 17:48
**/
@Slf4j
public class GoodsLockService {
int maxDeque = 5;
private LinkedBlockingQueue storeLinkedBlockingQueue = new LinkedBlockingQueue();
private Lock lock = new ReentrantLock();
private Condition fullCondition = lock.newCondition();
private Condition emptyCondition = lock.newCondition();
public GoodsLockService(LinkedBlockingQueue storeLinkedBlockingQueue) {
this.storeLinkedBlockingQueue = storeLinkedBlockingQueue;
}
public void producer(Long id){
lock.lock();
try{
if(storeLinkedBlockingQueue.size()>=maxDeque){
fullCondition.await();
}
emptyCondition.signalAll();
GoodsDto dto = new GoodsDto();
dto.setId(id);
dto.setGoodsName("商品:"+id);
dto.setCreateTime(new Date());
log.info("生成产品:{}",dto.toString());
storeLinkedBlockingQueue.add(dto);
}catch (Exception e){
log.error("消费产品异常:{}",e);
}finally {
lock.unlock();
}
}
public void consumer(){
int zero = 0;
lock.lock();
try{
if(storeLinkedBlockingQueue.size()<=zero){
emptyCondition.await();
}
fullCondition.signalAll();
GoodsDto dto = (GoodsDto) storeLinkedBlockingQueue.take();
log.info("消费产品:{}",dto.toString());
}catch (Exception e){
log.error("消费产品异常:{}",e);
}finally {
lock.unlock();
}
}
}
package com.cjw.concurrent.scxf.lock;
import lombok.extern.slf4j.Slf4j;
/**
* @author wucj
* @date 2019-06-27 17:45
**/
@Slf4j
public class ProducerLock implements Runnable{
private GoodsLockService goodsLockService;
public ProducerLock(GoodsLockService goodsLockService) {
this.goodsLockService = goodsLockService;
}
@Override
public void run() {
int maxCount = 10;
for(int i=0;i