没啥说的就是上一次的包子铺案例加入了封装,还把方法简化了下。
package cn.zsp.thread_05;
//wait() ; / /使用了wait就等待了。立即释放锁。将来醒过来的时候,是从这里醒过来的时候
public class BaoZiDemo {
public static void main(String[] args) {
BaoZiType baozi= new BaoZiType();
ConsumeBaozi1 b1= new ConsumeBaozi1(baozi);
ConsumeBaozi2 b2= new ConsumeBaozi2(baozi);
ProduceBaoZi b3=new ProduceBaoZi(baozi);
Thread prob=new Thread(b3);
Thread baozi1 =new Thread(b1);
Thread baozi2 =new Thread(b2);
prob.start();
baozi1.start();
baozi2.start();
}
}
package cn.zsp.thread_05;
public class BaoZiType {
private String baozi1="肉包";
private String baozi2="菜包";
private int number1=0;
private int number2=0;
private boolean flag;
public synchronized void consume1(){
if(number1<1 )
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("肉包子卖出去了一个");
number1--;
if(number1<5)
this.notify();
}
public synchronized void consume2(){
if(number2<1 )
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("菜包子卖出去了一个");
number2--;
if(number2<5)
this.notify();
}
public synchronized void product(){
if(number1>5 ||number2>5)
{
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("现在有"+number1+"个肉包子"+number2+"个菜包子");
number1+=3;
number2+=3;
this.notify();
}
}
package cn.zsp.thread_05;
public class ConsumeBaozi1 implements Runnable{
BaoZiType b=new BaoZiType();
public ConsumeBaozi1() {
}
public ConsumeBaozi1(BaoZiType b) {
this.b = b;
}
@Override
public void run() {
while(true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
b.consume1();
}
}
}
package cn.zsp.thread_05;
public class ConsumeBaozi2 implements Runnable {
BaoZiType b = new BaoZiType();
public ConsumeBaozi2() {
}
public ConsumeBaozi2(BaoZiType b) {
this.b = b;
}
public void run() {
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
b.consume2();
}
}
}
package cn.zsp.thread_05;
public class ProduceBaoZi implements Runnable {
BaoZiType b = new BaoZiType();
public ProduceBaoZi() {
}
public ProduceBaoZi(BaoZiType b) {
this.b = b;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
b.product();
}
}
}