//wait() ; / /使用了wait就等待了。立即释放锁。将来醒过来的时候,是从这里醒过来的时候
// b.notify(); 唤醒线程的方法
主方法:
package cn.zsp.thread_03;
//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_03;
public class BaoZiType {
String baozi1="肉包";
String baozi2="菜包";
int number1=0;
int number2=0;
}
一号包子的消费情况:
package cn.zsp.thread_03;
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();
}
synchronized (b) {
if (b.number1 <1) {
try {
b.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("肉包子卖出去了一个");
b.number1--;
b.notify();
}
}
}
}
package cn.zsp.thread_03;
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();
}
synchronized (b) {
if (b.number2<1) {
try {
b.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("菜包卖出去了一个");
b.number2--;
b.notify();
}
}
}
}
消费三号包子:
package cn.zsp.thread_03;
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();
}
synchronized (b) {
if (b.number1 > 5 || b.number2 > 5) {
try {
b.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("现在肉包子有"+b.number1+"个 菜包子有"+b.number2+"个");
b.number1 += 1;
b.number2 +=1 ;
b.notify();
}
}
}
}