多线程练习-熊吃蜂蜜
作者:互联网
要求
现在有一个罐子,两只熊,十只蜜蜂,每只蜜蜂每隔十秒产生一滴蜂蜜,熊大一次吃5滴蜂蜜,熊二一次吃10滴蜂蜜,吃完就不吃了。
实现
罐子的实现
static class Contanier {
private int honey;
public Contanier() {
}
public void add() {
synchronized (Contanier.class) {
honey += 1;
}
}
public Boolean eat(int appetite) {
synchronized (Contanier.class) {
if (honey / appetite > 0) {
honey -= appetite;
return true;
} else {
return false;
}
}
}
}
熊
static class Bear implements Runnable {
private int appetite;
private Contanier contanier;
Boolean eated = false;
public Bear(Contanier contanier, int appetite) {
this.contanier = contanier;
this.appetite = appetite;
}
@Override
public void run() {
while (!eated) {
eated = contanier.eat(appetite);
if (eated) {
System.out.println("熊" + Thread.currentThread().getName() + "吃到蜂蜜了,终止线程");
}
}
}
}
小蜜蜂
static class Bee implements Runnable {
private Contanier contanier;
public Bee(Contanier contanier) {
this.contanier = contanier;
}
@Override
public void run() {
while (true){
try {
Thread.sleep(10000);
contanier.add();
System.out.println("小蜜蜂"+Thread.currentThread().getName() +"生产了蜂蜜");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
执行方法
public static void main(String[] args) {
Contanier contanier = new Contanier();
for (int i= 0; i< 10; i++){
Thread thread = new Thread(new Bee(contanier), ""+i);
thread.start();
}
Thread bear1 = new Thread(new Bear(contanier,5), "大");
bear1.start();
Thread bear2 = new Thread(new Bear(contanier, 10), "二");
bear2.start();
}
运行效果
标签:contanier,Thread,Contanier,蜂蜜,new,appetite,多线程,public,熊吃 来源: https://blog.csdn.net/weixin_43125410/article/details/116701313