package com.tuling.learnjuc.sync.xiaoshanshan;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ProducerAndConsumerLock {
public static void main(String[] args) {
QueueLock queue =new QueueLock(5);
new Thread(new ProducerLock(queue)).start();
new Thread(new ConsumerLock(queue)).start();
new Thread(new ConsumerLock(queue)).start();
new Thread(new ConsumerLock(queue)).start();
new Thread(new ConsumerLock(queue)).start();
new Thread(new ConsumerLock(queue)).start();
new Thread(new ConsumerLock(queue)).start();
}
}
class QueueLock{
private Object[] array;
private int currentSize ;
private int putIndex ;
private int takeIndex ;
private ReentrantLock lock ;
private Condition notFull ;
private Condition notEmpty ;
public QueueLock(int capacity) {
array = new Object[capacity];
currentSize = 0;
lock = new ReentrantLock();
notFull =lock.newCondition();
notEmpty = lock.newCondition();
}
// 放数据
public void put(Object o){
lock.lock();
try{
while(currentSize== array.length){
try {
notFull.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
array[putIndex] = o ;
// if(++putIndex==array.length){
// putIndex = 0;
// }
if((putIndex+1)==array.length){
putIndex = 0;
}else{
putIndex = putIndex+1;
}
currentSize ++ ;
System.out.println(Thread.currentThread().getName() + "放入了"+o + "," + currentSize);
if(currentSize == array.length){
notEmpty.signalAll();
}
}finally {
lock.unlock();
}
}
// 取数据
public Object take(){
lock.lock();
try{
while(currentSize==0){
try {
notEmpty.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object ret = array[takeIndex];
if(null==ret){
System.out.println("没有取到对象");
return null;
}
array[takeIndex] = null ;
// if(++takeIndex==array.length){
// takeIndex = 0;
// }
if((takeIndex+1)==array.length){
takeIndex =0;
}else {
takeIndex = takeIndex+1 ;
}
currentSize -- ;
System.out.println(Thread.currentThread().getName() + "取出了"+ret + "," + currentSize);
if(currentSize == 0){
notFull.signalAll();
}
return ret;
}finally {
lock.unlock();
}
}
}
class ProducerLock implements Runnable{
QueueLock queue ;
public ProducerLock(QueueLock queue) {
this.queue = queue;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.put(new Random().nextInt(1000));
}
}
}
class ConsumerLock implements Runnable{
QueueLock queue ;
public ConsumerLock(QueueLock queue) {
this.queue = queue;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
queue.take();
}
}
}
java.util.concurrent类库中提供Condition类来实现线程之间的协调。调用Condition.await() 方法使线程等待,其他线程调用Condition.signal() 或 Condition.signalAll() 方法唤醒等待的线程。
注意:调用Condition的await()和signal()方法,都必须在lock保护之内。