package atguigu.java;
//店员
class Clerk{
private int ProductNum = 0;
//生产操作
public synchronized void produce() {
if(ProductNum < 20){
ProductNum++;
System.out.println(Thread.currentThread().getName()+":开始生产->编号:"+ProductNum);
// notify();
this.notify();
}else {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费操作
public synchronized void consume() {
if(ProductNum > 0){
System.out.println(Thread.currentThread().getName()+":开始消费->编号:"+ProductNum);
ProductNum--;
this.notify();
}else {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//生产者
class Productor implements Runnable{
private Clerk clerk = new Clerk();
@Override
public void run() {
while (true){
System.out.println(Thread.currentThread().getName()+":准备生产");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.produce();
}
}
}
//消费者
class Customer implements Runnable{
private Clerk clerk = new Clerk();
@Override
public void run() {
while (true){
System.out.println(Thread.currentThread().getName()+":准备消费");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
clerk.consume();
}
}
}
public class ProdectTest {
public static void main(String[] args) {
Productor productor = new Productor();
Customer customer = new Customer();
Thread tproductor = new Thread(productor);
Thread tcustomer = new Thread(customer);
tproductor.setName("生产者1");
tcustomer.setName("消费者1");
tproductor.start();
tcustomer.start();
}
}
这两个线程之间没有互相影响,生产者的notify()无法唤醒消费者的wait()
竞争的不是同一把锁