lock
- 这里的lock只需要一把锁
因为同时还要配合状态 一起决定
- 一定要在try里面用 一定要unlock
public class Test {
public static void main(String[] args) {
//传统版本
AirConditional airConditional = new AirConditional();
new Thread(()->{
for (int i = 0; i < 5; i++) {
airConditional.produce();
}
}).start();
new Thread(()->{
for (int i = 0; i < 5; i++) {
airConditional.consume();
}
}).start();
}
}
class AirConditional{
int temp ;
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void produce(){
try {
lock.lock();
while( temp != 0){
condition.await();
}
temp++;
System.out.println("生产后为"+temp);
condition.signalAll();
}catch (Exception e){
}
finally {
lock.unlock();
}
}
public void consume(){
try {
lock.lock();
while( temp != 1){
condition.await();
}
temp--;
System.out.println("消费后为"+temp);
condition.signalAll();
}catch (Exception e){
}
finally {
lock.unlock();
}
}
}