Desk类
package com.huanghun.demo10;
public class Desk {
public static int count = 10;
public static boolean flag;
public static final Object lock = new Object();
}
消费者Foodie类
package com.huanghun.demo10;
import sun.security.krb5.internal.crypto.Des;
public class Foodie extends Thread{
@Override
public void run() {
while (true){
synchronized (Desk.lock){
if(Desk.count == 0){
break;
}
else {
if(Desk.flag){
System.out.println("消费东西");
Desk.flag = false;
Desk.lock.notify();
Desk.count--;
}
else{
try {
Desk.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
生产者Cooker类
package com.huanghun.demo10;
import sun.security.krb5.internal.crypto.Des;
public class Cooker extends Thread{
@Override
public void run() {
while (true){
synchronized (Desk.lock){
if(Desk.count == 0){
break;
}
else{
if(!Desk.flag){
System.out.println("生产东西");
Desk.flag = true;
Desk.lock.notifyAll();
}
else {
try {
Desk.lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}
Demo类
package com.huanghun.demo10;
public class Demo {
public static void main(String[] args) {
Cooker cooker = new Cooker();
Foodie foodie = new Foodie();
cooker.start();
foodie.start();
}
}