A.加锁的对象、调用wait()的对象、调用notify()的对象,这三者是一个对象
B.生产者和消费者加锁的对象必须是同一个对象
class shared_Resource{
private int num=0;
public synchronized void decrement() {
while(num==0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"消费1个");
num--;
this.notifyAll();
}
public synchronized void increment(){
while(num!=0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName()+"生产1个");
num++;
this.notifyAll();
}
}
public class producerAndConsumer {
public static void main(String[] args) {
shared_Resource resource=new shared_Resource();
new Thread(()->{
for(int i=0;i<6;i++) resource.increment();
},"生产者").start();
for(int i=0;i<6;i++)
{
new Thread(()->{
try {
Thread.sleep(100);
resource.decrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
},"消费者"+String.valueOf(i)).start();
}
}
}