当货物2个的时候销售,还剩一个的时候生产
要点:在生产中等待销售,在销售中等待生产
生产者与消费者
public class A {
int num;
public int getNum() {
return num;
}
//生产产品的方法;
public synchronized void produce(){
num++;
System.out.println("生产了一个产品………………");
this.notify();
}
//销售产品的方法:
public synchronized void sale(){
num--;
System.out.println("销售了一个产品………………");
this.notify();
}
//等待生产的方法;在生产中等待销售;
public synchronized void waitforproduce() throws InterruptedException{
while(num<=1){
this.wait();
}
}
//等待销售的方法;在销售中等待生产;
public synchronized void waitforsale() throws InterruptedException{
while(num>=2){
this.wait();
}
}
}
package org.hyx;
public class Produce implements Runnable{
A a;
public Produce(A a){
this.a=a;
}
@Override
public void run() {
while(true){
try {
a.waitforsale();
System.out.println("正在生产品中………………");
a.produce();
System.out.println("当前还剩下产品数量为:"+a.getNum()+"个");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package org.hyx;
public class Sale implements Runnable{
A a;
public Sale(A a){
this.a=a;
}
@Override
public void run() {
while(true){
try {
Thread.sleep(100);
a.waitforproduce();
System.out.println("正在销售产品中………………");
a.sale();
System.out.println("当前剩下的数量为:"+a.getNum()+"个");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package org.hyx;
public class Test {
public static void main(String[] args) throws InterruptedException {
A a=new A();
Produce p=new Produce(a);
Sale s=new Sale(a);
Thread t=new Thread(p);
Thread tt = new Thread(s);
t.start();tt.start();
Thread.sleep(2000);
System.exit(0);
}
}