package xianTest;
public class Ceshi {
public static void main(String[] args) {
dian Dian = new dian();
xiao xiao = new xiao(Dian);
xiao.setName("消费者");
chan chan = new chan(Dian);
chan.setName("生产者");
chan.start();
xiao.start();
}
}
//消费者xiao
class xiao extends Thread{
private dian Dian;
public xiao(dian Dian){
this.Dian = Dian;
}
@Override
public void run() {
System.out.println("开始消费产品");
while (true){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
Dian.xx();
}
}
}
//生产者chan
class chan extends Thread{
private dian Dian;
public chan(dian Dian){
this.Dian = Dian;
}
@Override
public void run() {
System.out.println("开始生产产品");
while (true){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
Dian.cc();
}
}
}
//店员dian
class dian{
private int liang = 0;
//生产产品
public synchronized void cc(){
if (liang <20) {
liang++;
System.out.println("生产了产品:"+liang);
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//消费产品
public synchronized void xx(){
if (liang >0) {
System.out.println("消费了产品:"+liang);
liang--;
notify();
}else{
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}