前置知识
LinkedList和ArrayList的区别
不谈细节,最根本的区别从名字上就可以看出来
LinkedList实现的是Link,是链表结构
ArrayList实现的是Array ,是数组结构
-------------------------------------------------------------
本文选用LinkedList作为消费者生产者模式的容器
使用ReentranceLock实现消费者生产者模式
消费者类
public class Consumer {
int countMax = 10;
public void start(LinkedList<String> list, Lock lock, Condition condition) {
new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
Thread.sleep(2000);
lock.lock();
if (list.size()<=0) {
condition.await();
}
System.out.println("take==>"+list.p+"当前size==>"+list.size());
condition.signal();
lock.unlock();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();;
}
}
生产者类:
public class Producer {
int countMax = 10;
private int object = 0;
public void start(LinkedList<String> list, Lock lock, Condition condition) {
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while(true) {
try {
Thread.sleep(1000);
lock.lock();
if (list.size()>=countMax) {
condition.await();
}
list.push(++object+"");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("put==>"+object+"当前size==>"+list.size());
condition.signal();
lock.unlock();
}
}
}).start();;
}
}
Main类
public class Main {
private static LinkedList<String> list = new LinkedList<>();
private static Lock lock = new ReentrantLock();
private static Condition condition = lock.newCondition();
public static void main(String args[]) {
Consumer consumer = new Consumer();
Producer producer = new Producer();
producer.start(list,lock,condition);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
consumer.start(list,lock,condition);
}
}
-----------------------------------------------------------------------------------------------------------
备注:LinkedBlockingQueue也是用Lock 实现的
性能优化:使用两个锁,入队用一把锁,出队用一把锁
参考:
http://www.importnew.com/27063.html
https://blog.csdn.net/xindoo/article/details/80004003