//模拟生产者生产
class Productor implements Runnable{
MyQueue queue;
public Productor(MyQueue queue){
this.queue=queue;
}
@Override
public void run() {
for(int i=0;i<1000;i++){
try {
Thread.sleep(100);
queue.put(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//模拟消费者消费
class Consumer implements Runnable{
MyQueue queue;
public Consumer(MyQueue queue){
this.queue=queue;
}
@Override
public void run() {
for(int i=0;i<1000;i++){
try {
Thread.sleep(100);
queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class MyQueue{
Lock lock=new ReentrantLock();
Condition pro=lock.newCondition();
Condition con=lock.newCondition();
Object[] arr=new Object[100];
int capacity=100;
int putIndex;
int takeIndex;
int count;
public void put(Object o){
try{
lock.lock();
while(count==capacity){
System.out.println("已经满了,目前为"+count);
pro.await();
}
arr[putIndex++]=o;
System.out.println("生产者生产"+o);
if(putIndex>=capacity){
putIndex=0;
}
count++;
con.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void take(){
try{
lock.lock();
while(0==count){
System.out.println("现在为空"+count);
con.await();
}
Object ret=arr[takeIndex++];
System.out.println("消费者消费"+ret);
if(takeIndex>=capacity){
takeIndex=0;
}
count--;
con.signal();
}catch (InterruptedException e) {
e.printStackTrace();
} finally{
lock.unlock();
}
}
}
public class Test {
public static void main(String[] args) throws Exception {
MyQueue queue=new MyQueue();
new Thread(new Productor(queue)).start();
new Thread(new Productor(queue)).start();
new Thread(new Consumer(queue)).start();
}
}
10-16
9293