public class a01_Lock<T> {
//生产的东西
final private LinkedList<T> lists = new LinkedList<T>();
//能够放的最大数量
final private int MAX = 10;
//数量
private int count = 0;
//锁
private Lock lock = new ReentrantLock();
//生产者队列
private Condition producer = lock.newCondition();
//消费者队列
private Condition consumer = lock.newCondition();
//生产方法
public void put(T t) {
try {
lock.lock();
while (lists.size() == MAX) {
producer.await();
}
lists.add(t);
++count;
consumer.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//消费方法
public T get() {
T t = null;
try {
lock.lock();
while (lists.size() == 0) {
consumer.await();
}
t = lists.removeFirst();
--count;
producer.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return t;
}
}
ReentrantLock实现消费者生产者
最新推荐文章于 2024-02-28 08:40:32 发布