- wait notifyAll 实现同步容器
public class Container1<T > {
final private LinkedList<T> list = new LinkedList<>();
final private int Max = 10;
private int count = 0;
public synchronized void put(T t){
while (list.size() == Max){ // while if 区别
try {
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
list.add(t);
++ count;
this.notifyAll();// 通知消费者线程消费
}
public synchronized T get(){
T t = null;
while (list.size() == 0){
try {
this.wait();
}catch (InterruptedException e){
e.printStackTrace();
}
}
t = list.removeFirst();
count -- ;
this.notifyAll();//通知生产者生产
return t;
}
}
注意: wait 会释放锁, notify不会释放锁
为什么使用 while 而不使用 if ?
while每次都会检查完条件再往下执行,if 不会
- ReentrantLock Condition 实现同步容器
public class Container2<T > {
final private LinkedList<T> list = new LinkedList<>();
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 (list.size() == Max){ // while if 区别
producer.await();
}
list.add(t);
++ count;
consumer.signalAll();// 通知消费者线程消费
}catch (InterruptedException e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public T get(){
T t = null;
try {
lock.lock();
while (list.size() == 0){
consumer.await();
}
t = list.removeFirst();
count -- ;
producer.signalAll();//通知生产者生产
}catch (InterruptedException e){
e.printStackTrace();
}finally {
lock.unlock();
}
return t;
}
}