生产者消费者(旧)
class AirConditioner
{
private int number=0;
public synchronized void increment() throws InterruptedException{
while (number!=0){
this.wait();
}
number++;
System.out.println(Thread.currentThread().getName()+" "+number);
this.notifyAll();
}
public synchronized void decrement() throws InterruptedException{
while (number==1){
this.wait();
}
number--;
System.out.println(Thread.currentThread().getName()+" "+number);
this.notifyAll();
}
}
public class ThreadWaitNotifyDemo {
public static void main(String[] args) {
AirConditioner airConditioner = new AirConditioner();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
airConditioner.increment();
}catch (InterruptedException e){
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
airConditioner.decrement();
}catch (InterruptedException e){
e.printStackTrace();
}
}
},"B").start();
}
}
生产者消费者(新)

import com.sun.org.apache.xpath.internal.objects.XNumber;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class AirConditioner1
{
private int number=0;
private Lock lock=new ReentrantLock();
private Condition condition=lock.newCondition();
public void increment() throws InterruptedException{
lock.lock();
try {
while (number!=0){
condition.await();
}
number++;
System.out.println(Thread.currentThread().getName()+" "+number);
condition.signalAll();
}catch (InterruptedException e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void decrement() throws InterruptedException{
lock.lock();
try {
while (number==0){
condition.await();
}
number--;
System.out.println(Thread.currentThread().getName()+" "+number);
condition.signalAll();
}catch (InterruptedException e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public class ThreadWaitNotifyNew {
public static void main(String[] args) {
AirConditioner1 airConditioner = new AirConditioner1();
new Thread(()->{
for (int i = 0; i < 10; i++) {
try {
airConditioner.increment();
}catch (InterruptedException e){
e.printStackTrace();
}
}
},"A").start();
new Thread(()->{
for (int i = 0; i <10; i++) {
try{
airConditioner.decrement();
}catch (InterruptedException e){
e.printStackTrace();
}
}
},"B").start();
}
}